用于在同一用户的单行中显示重复日期的SQL查询

时间:2018-03-06 06:55:56

标签: sql pivot crosstab

请帮我解决SQL查询





这是我的表




  +  - ------ + ---------- +
 | UserID | Date |
 + -------- + --------- -  +
 | Sanjay | 29/06/2017 |
 + -------- + ---------- +
 | Sanjay | 30/06 / 2017 |
 + -------- + ---------- +
 | Sanjay | 26/06/2017 |
 + ---- ---- + ---------- +
 | Vishal | 29/06/2017 |
 + -------- + ------- --- +
 | Vishal | 30/06/2017 |
 + -------- + ---------- +
 | Vasanti | 29 / 06/2017 |&#XA + -------- + ---------- +
  




需要以下输出




  + -------- + ---------- + ---- -------- + ------------ + ----------- ----------- + + ---- ---- +
 | UserID | Count | Date 1 | Date 2 | Date 3 | Date 4 | Date 5 |
 + -------- + ------- --- + ------------ + ------------ + ----------- + -------- --- + -------- +
 | Sanjay | 3 | 29/06/2017 | 30/06/2017 | 26/06/2017 | | |&#XA + -------- + ---------- + ------------ + ----------- -  + ----------- + ----------- + -------- +
 | Vishal | 2 | 29/06/2017 | 30/06/2017 | | | |&#XA + -------- + ---------- + ------------ + ----------- -  + ----------- + ----------- + -------- +
 | Vasanti | 1 | 29/06/2017 | | | | |&#XA + -------- + ---------- + ------------ + ----------- -  + ----------- + ----------- + -------- +
  
&#XA ;

1 个答案:

答案 0 :(得分:1)

SQL Server有 PIVOT 运算符,可以执行此类任务

with cte as
(
    select *, count(userid) over (partition by userid) Counts,
              concat('Date ', row_number() over (partition by UserID  order by (SELECT 1))) SQ
    from table
)

select * from 
(
    select * from cte
)a 
PIVOT (
    MAX(Dates) for SQ IN ([Date 1], [Date 2], [Date 3])
)P
order by 2 desc

全动态枢轴方式

declare @cols varchar(200), @query varchar(2000)

SET @cols = STUFF(
                  (select DISTINCT  ','+QUOTENAME(concat('Date ', row_number() over (partition by UserID  order by (SELECT 1))))
                   from table for xml path('')),1,1, '')

set @query  = 'select * from 
               (
                  select *, 
                         count(userid) over (partition by userid) Counts,
                         concat(''Date '', row_number() over (partition by UserID  order by (SELECT 1))) SQ
                  from table
               )a PIVOT (
                    MAX(Dates) for SQ IN ('+@cols+'))P
               order by 2 desc'

exec (@query)

结果:

UserID  Counts  Date 1      Date 2      Date 3
Sanjay  3       29/06/2017  30/06/2017  26/06/2017
Vishal  2       29/06/2017  30/06/2017  NULL
Vasant  1       29/06/2017  NULL        NULL