SQL Pivot选择多行

时间:2018-08-30 07:12:45

标签: sql sql-server tsql pivot unpivot

这是我的桌子:

Tasble for pivot looks like this

我想这样创建数据透视表: enter image description here

我写了一些查询,但对角仅得到名称:

(
select 
[1] as Client0, 
[2] as Client1, 
[3] as Client2, 
[4] as Client3,
[5] as Client4
from 
(
select 
    rc.DateCreated, 
    gd.Name,
    DENSE_RANK() over (order by gd.ID_TableGD) as colnum
from TableGD gd
inner join TableRC rc ON gd.ID_TableGD = rc.ID_TableRC
WHERE gd.ID_TableGD IN (962,1029,1024) 
AND gd.Active = 1
) as t
pivot
(
MAX(Name)
for colnum in 
(
[1],
[2],
[3],
[4],
[5]

)
) as pvt) 

因此,我希望特定的客户端能够在同一列中获取clientName(ClientA)和CreatedDate。

这是我的第一个关键点,我不确定是否需要输入Max(Name)?

我得到这样的表: enter image description here

2 个答案:

答案 0 :(得分:2)

我将Valueunpivot一起使用。

首先,您需要执行DateCreated,将NameSELECT v.* FROM T t1 CROSS APPLY( VALUES (Name,colnum,1), (CAST(DateCreated AS VARCHAR(50)),colnum,2) ) v (val,colnum,grp) 放在一列中,这是您预期的结果。

让结果看起来像这样。

|        val | colnum | grp |
|------------|--------|-----|
|    ClientA |      1 |   1 |
| 2018-08-21 |      1 |   2 |
|    ClientB |      2 |   1 |
| 2018-08-22 |      2 |   2 |
|    ClientC |      3 |   1 |
| 2018-08-23 |      3 |   2 |

结果

Pivot

下一步,您可以尝试使用CREATE TABLE T( Name VARCHAR(50), DateCreated DATE, colnum INT ); INSERT INTO T VALUES('ClientA','2018-08-21',1); INSERT INTO T VALUES('ClientB','2018-08-22',2); INSERT INTO T VALUES('ClientC','2018-08-23',3); 让垂直数据变为水平数据。

SELECT 
    MAX(CASE WHEN v.colnum = 1 THEN v.val end) client0,
    MAX(CASE WHEN v.colnum = 2 THEN v.val end) client1,
    MAX(CASE WHEN v.colnum = 3 THEN v.val end) client2,
    MAX(CASE WHEN v.colnum = 4 THEN v.val end) client3,
    MAX(CASE WHEN v.colnum = 5 THEN v.val end) client4
FROM T t1 CROSS APPLY(
    VALUES 
    (Name,colnum,1),
    (CAST(DateCreated AS VARCHAR(50)),colnum,2)
) v (val,colnum,grp)
group by grp

查询1

|    client0 |    client1 |    client2 | client3 | client4 |
|------------|------------|------------|---------|---------|
|    ClientA |    ClientB |    ClientC |  (null) |  (null) |
| 2018-08-21 | 2018-08-22 | 2018-08-23 |  (null) |  (null) |

Results

FORMAT

CROSS APPLY ... Value

注意

如果要显示原始的日期时间格式。

您可以使用CONVERTFORMAT转换期望的日期时间格式。

此示例适用于format http://sqlfiddle.com/#!18/12ae9e/3

尽管Convert比{{1}}更易于使用,但涉及多个数据时性能却很差。

答案 1 :(得分:1)

在选择时间中使用最大值,如下所示:

select 
max([1]) as Client0, 
max([2]) as Client1, 
max([3]) as Client2, 
max([4]) as Client3,
max([5]) as Client4
from 
(
select 
    rc.DateCreated, 
    gd.Name,
    DENSE_RANK() over (order by gd.ID_TableGD) as colnum
from TableGD gd
inner join TableRC rc ON gd.ID_TableGD = rc.ID_TableRC
WHERE gd.ID_TableGD IN (962,1029,1024) 
AND gd.Active = 1
) as t
pivot
(
MAX(Name)
for colnum in 
(
[1],
[2],
[3],
[4],
[5]

)
) as pvt