订购最少距离getdate

时间:2013-01-23 10:37:19

标签: sql date sql-order-by date-range

我有这张桌子

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

我想通过距离desc订购距离getdate(无论Id_Subscription)最小距离的用户。例如:

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 个答案:

答案 0 :(得分:3)

您可以将ABSDatediff一起使用,例如:

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子句中使用OVER(未经测试,使用SQL-Server> = 2005):

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 

DEMO

答案 1 :(得分:0)

尝试此查询。这是Sql-fiddle example

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

答案 2 :(得分: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 |

这是fiddle link

答案 3 :(得分: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`