SQL Server Rank()按日期,分组和连接两个表,包括分页

时间:2017-04-07 10:31:17

标签: sql sql-server database tsql group-by

在SQL Server中使用这两个表:

购物车

id    userid    prodid    qt    date
1     21        P1        1     2017-02-18
2     21        P8        1     2017-02-19
3     21        P2        1     2017-02-20
4     22        P5        1     2017-02-21
5     22        P3        1     2017-02-22
6     23        P4        1     2017-02-23

用户

id    user_name
21    John
22    James
23    Alice
24    Lily

我想要一张只显示最新日期的文章的表格,按user_id分组,有1列(art_c),每个用户添加到shopcart的文章数量(不是Qt,即数量) ),并加入用户表。 此外,我想为每行结果添加分页。

我想要的结果是这样的:

id    userid    user_name    prodid   art_c   date
3     21        John         P2       3       2017-02-20
5     22        James        P3       2       2017-02-22
6     23        Alice        P4       1       2017-02-23

最好/最快的方法是什么? 我正在使用这个请求,我不确定它是否是好的/快速的方式:

With tb_a as 
(
  SELECT u_id,u_name,dat,art_c,ROW_NUMBER() OVER (ORDER BY u_name) as rgw FROM
  shopcart a
  LEFT JOIN 
  (SELECT 
       a.userid as u_id,
       b.user_name as u_name,
       Format(shop_date, 'dd.MM.yyyy HH:mm') as dat,
       RANK() OVER (PARTITION BY a.userid ORDER BY shop_date DESC) as dest_rank,
       Count(a.id) OVER (PARTITION BY a.userid ORDER BY shop_date) as art_c
       FROM 
            shopcart a
       LEFT JOIN 
            Users b on a.userid=b.id
  group by 
       a.userid,b.name,shop_date,a.id) b on a.userid=b.u_id 
  where dest_rank = 1
  group by u_id,u_name,dat,art_c
)

SELECT * FROM tb_a
WHERE rgw BETWEEN 0 AND 100 order by rgw

3 个答案:

答案 0 :(得分:3)

我认为您只需要在row_number()上使用ShopCart。我会在join

之前完成
select u.*, sc.*
from (select sc.*,
             row_number() over (partition by sc.userid order by date desc) as seqnum
      from ShopCart sc
     ) sc join
     users u
     on sc.userid = u.id
where seqnum = 1;

对于分页,您可以添加order by,然后可以使用offsetfetch next

编辑:

您也可以使用窗口函数获取计数:

select u.*, sc.*
from (select sc.*,
             row_number() over (partition by sc.userid order by date desc) as seqnum,
             count(*) over (partition by sc.userid) as cnt
      from ShopCart sc
     ) sc join
     users u
     on sc.userid = u.id
where seqnum = 1;

答案 1 :(得分:1)

与声明和 Row_Number 一起使用如下所示, PartNo 列将按userId对您的数据进行分组, SeqNo 列获取用户明智的数字:

;WITH S AS
(
    SELECT 
        *,
        COUNT(Id) OVER (PARTITION BY UserId) AS PartNo,
        ROW_NUMBER() OVER (PARTITION BY UserId Order BY Date DESC) AS SeqNo
    FROM @ShopCart SC
)

SELECT
    S.Id,
    S.UserId,
    U.UserName  ,
    S.ProdId,
    S.PartNo AS Art_c,
    S.Date
FROM S
LEFT JOIN @User U ON S.UserId=U.Id
WHERE S.SeqNo=1

答案 2 :(得分:0)

ID
-----------
5055
5056
5057