SQL-如何将行更改为列? (PIVOT)

时间:2019-10-14 21:35:19

标签: sql tsql pivot

如何将这些行更改为列?

这是我的查询

SELECT [FEC_FIS], [ESTADO_DESC], COUNT(1)
FROM [DATABASE].[dbo].[TABLE]
WHERE FEC_FIS >= CONVERT(DATE,GETDATE()-7) AND ESTADO IN (2,8)
GROUP BY [FEC_FIS],[ESTADO_DESC]
ORDER BY FEC_FIS

enter image description here

这是我的

enter image description here

2 个答案:

答案 0 :(得分:1)

使用条件聚合:

SELECT 
    [FEC_FIS], 
    SUM(
        CASE
            WHEN [ESTADO_DESC] = 'PROCESADO CON ERROR' THEN 1 
            ELSE 0 
        END
    ) [PROCESADO CON ERROR],
    SUM(
        CASE
            WHEN [ESTADO_DESC] = 'TICKET REPROCESADO' THEN 1 
            ELSE 0 
        END
    ) [TICKET REPROCESADO]
FROM [DATABASE].[dbo].[TABLE]
WHERE [FEC_FIS] >= CONVERT(DATE,GETDATE()-7) AND [ESTADO] IN (2,8)
GROUP BY [FEC_FIS]

答案 1 :(得分:1)

尝试以下查询...

 select * from (
    select [FEC_FIS], [ESTADO_DESC] from [DATABASE].[dbo].[TABLE] 
WHERE [FEC_FIS] >= CONVERT(DATE,GETDATE()-7) AND [ESTADO] IN (2,8)
GROUP BY [FEC_FIS],[ESTADO_DESC]
    )
    PIVOT
    (
    count(YOUR_COUNT_COLOUMN_ID) for ESTADO_DESC in ('PROCESADO CON ERROR','TICKET REPROCESADO')
    )