SQL 旋转 select 多行

SQL Pivot select multiple rows

这是 table 我有:

我想像这样创建枢轴:

我写了一些查询,但我只得到对角线的名字:

(
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)?

我得到 table 是这样的:

在选择时使用最大值如下:

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

我会使用 CROSS APPLYValue 来做到这一点。

首先,您需要执行 unpivot 让您的 DateCreatedName 在一栏中,这是您的预期结果。

让结果看起来像这样。

SELECT 
  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);

查询 1:

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

Results:

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

CROSS APPLY ... Value

注意

如果您想显示原始日期时间格式。

您可以使用 CONVERT or FORMAT 来翻译您期望的日期时间格式。

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

虽然formatConvert好用,但在处理多个数据时性能较差。