我会用
CROSS APPLY
具有
Value
去做那件事。
unpivot
让你的
DateCreated
Name
在一列中,这是您的预期结果。
让结果像这样。
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
或
FORMAT
此示例用于
FORMAT
http://sqlfiddle.com/#!18/12ae9e/3
尽管
format
使用起来比
Convert