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

我想通过距离 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

4 回答 4

3

您可以使用ABSwith 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 BYOVER子句中使用,例如(未测试,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 

演示

于 2013-01-23T10:45:26.463 回答
0

试试这个查询。这是Sql-fiddle 示例

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
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 回答
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 回答