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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用于在同一用户的单行中显示重复日期的SQL查询相关的知识,希望对你有一定的参考价值。

请帮我解决SQL Query问题

这是我的表

+--------+----------+
|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|
+--------+----------+

需要低于所需的输出

+--------+----------+------------+------------+-----------+-----------+--------+
|UserID  |Count     |Date 1      |Date 2      |Date 3     |Date 4     |Date 5  |
+--------+----------+------------+------------+-----------+-----------+--------+
|Sanjay  |3         |29/06/2017  |30/06/2017  |26/06/2017 |           |        |
+--------+----------+------------+------------+-----------+-----------+--------+
|Vishal  |2         |29/06/2017  |30/06/2017  |           |           |        |
+--------+----------+------------+------------+-----------+-----------+--------+
|Vasanti |1         |29/06/2017  |            |           |           |        |
+--------+----------+------------+------------+-----------+-----------+--------+
答案

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

以上是关于用于在同一用户的单行中显示重复日期的SQL查询的主要内容,如果未能解决你的问题,请参考以下文章

用于获取重复记录并在 Gridview 中显示为一行的 SQL 查询

由 SQL 完成的查询多次显示相同的结果(查询中同一记录的多个副本)

使用单行函数

加密解密,MySQL单行函数,数学函数字符串日期时间,流程控制,完整详细可收藏查询SQL

如何将 UNION ALL 查询的结果显示为链接?

Oracle_SQL 单行函数