T-SQL在单个列下应用两行的数据透视表

时间:2017-10-23 15:10:00

标签: sql-server tsql pivot

在SQL Server 2014上,我使用以下代码:

CREATE TABLE TempTable
(
LType varchar(255),
LStatus varchar(255),
PAmount decimal(16,2),
RAmount decimal(16,2));

INSERT INTO TempTable (LType, LStatus, PAmount, RAmount)

VALUES ('TypeA','StatusA', '1000', '10'),
       ('TypeB', 'StatusC', '500', '50'),
       ('TypeC', 'StatusB', '2500', '100'),
       ('TypeB', 'StatusB', '1000', '50'),
       ('TypeA', 'StatusA', '3000', '25'),
       ('TypeC', 'StatusB', '2200', '50');



       Select Ltype, Lstatus, SUM(PAmount) as PAmount, SUM(RAmount) as RAmount

        From TempTable 

        Where PAmount > 0 
        Group By LType, LStatus

获取此表: enter image description here

我想要达到的目标是: enter image description here

我使用pivot但无法同时为状态列下的PAmount和RAmount应用它。 任何人都可以帮忙解决方案吗?

1 个答案:

答案 0 :(得分:2)

您可以使用条件聚合。这假设您将始终拥有这些值。如果你需要它是动态的,那么还有一些工作要做。

select StatusA_PAMount = max(case when Totals.Lstatus = 'StatusA' then Totals.PAmount end)
    , StatusA_RAMount = max(case when Totals.Lstatus = 'StatusA' then Totals.RAmount end)
    , StatusB_PAMount = max(case when Totals.Lstatus = 'StatusB' then Totals.PAmount end)
    , StatusB_RAMount = max(case when Totals.Lstatus = 'StatusB' then Totals.RAmount end)
    , StatusC_PAMount = max(case when Totals.Lstatus = 'StatusC' then Totals.PAmount end)
    , StatusC_RAMount = max(case when Totals.Lstatus = 'StatusC' then Totals.RAmount end)
from 
(
    Select Lstatus
        , SUM(PAmount) as PAmount
        , SUM(RAmount) as RAmount
    From TempTable 
    Where PAmount > 0 
    Group By LStatus
) Totals