0

私はこのテーブルを持っています

Id_User Id_Subscription Date_Expiration
1       1               2013-01-21
1       2               2013-01-28    
2       1               2013-01-15
2       2               2013-01-30
2       3               2013-01-31

getdateから(Id_Subscriptionに関係なく)最小距離のユーザーを距離descで注文したい。例:

Position Id_User   Distance in day
1        2         7
2        1         2

私はそれをやろうとしました

SELECT  ROW_NUMBER() OVER(ORDER BY COALESCE(MIN(us.Date_Expiration), 
CAST('2015-01-29 16:30:23.000' AS DATE)) DESC, us.id_user) AS Row, us.id_user
FROM User_Subscription us
GROUP BY a.Id_Anagrafica

しかし、それは正しくありません。

4

4 に答える 4

3

たとえば、次のようにABS使用できます。Datediff

SELECT Row_number() 
         OVER( 
           ORDER BY Abs(Datediff(dd, Getdate(), Date_Expiration)) ASC, 
         us.id_user) AS Row, 
       us.id_user 
FROM   user_subscription us 

質問を完了するため。各ユーザーの最大距離(日数)が必要だと思います。したがって、たとえばPARTION BY、句で使用できます(SQL-Server> = 2005ではテストされていません)。OVER

WITH cte 
     AS (SELECT Position = Row_number() 
                             OVER( 
                               partition BY id_user 
                               ORDER BY Abs(Datediff(dd, Getdate(), 
                             date_expiration ) 
                             ) 
                             DESC), 
                id_user, 
                [Distance in day] = Abs(Datediff(dd, Getdate(), date_expiration) 
                                    ) 
         FROM   user_subscription) 
SELECT position, 
       id_user, 
       [distance in day] AS [Max Distance in day] 
FROM   cte 
WHERE  position = 1 

デモ

于 2013-01-23T10:45:26.463 に答える
0

このクエリを試してください。これがSQLフィドルの例です

select row_number() over(order by numberofdays desc) position, 
           Id_User, numberofdays 
from (
     select Id_User, abs(datediff(day, getdate(), Date_Expiration )) numberofdays,
            rank() over (partition by Id_User order by abs(datediff(day, getdate(),  Date_Expiration )) ) rnk
     from user_subscription
    ) A
where rnk = 1


--Results
POSITION    ID_USER NUMBEROFDAYS
1           2        7
2           1        2
于 2013-01-23T10:47:24.597 に答える
0

次のテーブル構造で

create table user1(id_user number,id_sub number,date_exp date);

これを試して :

select row_number()   OVER (ORDER BY user1.id_user) position,id_user,MAX(date_exp)-MIN(date_exp) Max_Distance_in_day from user1 group by id_user;

出力付き:

| POSITION | ID_USER | MAX_DISTANCE_IN_DAY |
--------------------------------------------
|        1 |       1 |                   7 |
|        2 |       2 |                  16 |

これがフィドルリンクです

于 2013-01-23T11:00:13.580 に答える
0
select 
       ROW_NUMBER() over (order by min(abs(datediff(d,date_expiration,getdate()))) desc) [rank]
       ,id_user
       ,min(abs(datediff(d,date_expiration,getdate()))) as distance
from User_Subscription
group by id_user`
于 2013-01-23T11:53:52.860 に答える