sql复杂行到列的转换

时间:2019-09-03 13:33:50

标签: sql sql-server tsql

我有以下数据:

DECLARE @TBL TABLE (ID INT, Numb VARCHAR(10),   City VARCHAR(10),   Dates DATE)
INSERT INTO @TBL VALUES 
(101,'S1','AA','2019-07-20'),(101,'S2','BB','2019-05-03'),(101,'S2','AA','2019-07-31'),
(101,'S1','BB','2019-02-02'),(101,'S1','CC','2019-08-02'),(101,'S2','AA','2019-08-09'),
(101,'S2','CC','2019-06-20'),(101,'S3','CC','2019-08-02'),(101,'S2','AA','2019-05-26'),
(101,'S1','CC','2019-01-15'),(101,'S2','AA','2019-07-15'),(101,'S1','AA','2019-04-15'),
(101,'S3','CC','2019-06-05'),(101,'S2','CC','2019-02-14') ,(102,'S3','AA','2019-04-06') ,
(102,'S2','AA','2019-03-09'),(102,'S1','BB','2019-06-11'),(102,'S1','AA','2019-04-08'),
(102,'S3','CC','2019-02-24'),(102,'S2','CC','2019-04-22'),(102,'S3','BB','2019-02-14'),
(102,'S2','AA','2019-04-19')

我编写了一个查询,该查询基于City列计算Numb的数量,如下所示:

SELECT distinct
 ID 
, CASE WHEN Numb = 'S1' THEN COUNT(City) END AS 'S1_No'
, CASE WHEN Numb = 'S1' THEN max(Dates) END AS 'S1_Date'
, CASE WHEN Numb = 'S2' THEN COUNT(City) END AS 'S2_No'
, CASE WHEN Numb = 'S2' THEN max(Dates) END AS 'S2_Date'
, CASE WHEN Numb = 'S3' THEN COUNT(City) END AS 'S3_No'
, CASE WHEN Numb = 'S3' THEN max(Dates) END AS 'S3_Date'
FROM @TBL
 GROUP BY ID,Numb

当前输出

enter image description here 期望的输出 enter image description here

我希望所有case语句数据都基于其ID放在同一行中。 我试过枢轴,但没有运气。我可以通过查询编写任何方式以获得所需的输出吗? 谢谢

1 个答案:

答案 0 :(得分:3)

感谢您发布此类易消耗的示例数据。我希望每个人都说清楚。您超级亲密,朝着正确的方向前进。只需轻轻一点就能越过终点线。

这将产生您想要的预期输出。

SELECT ID 
    , count(CASE WHEN Numb = 'S1' THEN 1 END) AS S1_No
    , MAX(CASE WHEN Numb = 'S1' THEN Dates END) AS S1_Date
    , count(CASE WHEN Numb = 'S2' THEN 1 END) AS S2_No
    , max(CASE WHEN Numb = 'S2' THEN Dates END) AS S2_Date
    , count(CASE WHEN Numb = 'S3' THEN 1 END) AS S3_No
    , max(CASE WHEN Numb = 'S3' THEN Dates END) AS S3_Date
FROM @TBL
GROUP BY ID