SQL Pivot条件

时间:2015-08-12 14:28:25

标签: sql sql-server sql-server-2008

我已经编写了下面的代码来根据它出现的年份来计算总和值。这是我在下面的数据集之前的结果:

Cust    Year    YTD FY      Value
---------------------------------
Aspire  2015    YTD NULL    35.00
Aspire  2015    YTD NULL    6.00
Aspire  2014    YTD FY      20.00
Aspire  2014    YTD NULL    4.00

这是我目前的支点结果:

Cust    YTD     FY      2014    2015
-------------------------------------
Aspire  YTD     NULL    NULL    41.00
Aspire  YTD     FY      20.00   NULL
Aspire  YTD     NULL    4.00    NULL

枢轴工作,但我想进一步将列合并到下面的视图:

Cust    2014FY  2014YTD     2015
---------------------------------
Aspire  20.00   24.00       41.00

第1栏 - '2014FY'(列将是2014年所有分类为“YTD”的值)

第2栏 - '2014YTD'(列将是2014年所有分类'FY'的值)

SELECT  ACM.CustomerName,IG.Year AS Years, 
        CASE 
            WHEN IG.Period <= 8 THEN 'YTD'
        END AS 'YTDDataType',
        CASE 
            WHEN IG.Year = 2014 THEN 'FY'
        END AS 'FYDataType',
        IG.NetValue AS NetValue

FROM    Invoice AS IG INNER JOIN
        AccountCustomer AS ACM
            ON IG.AccountNumber = ACM.AccountNumber

WHERE   (IG.Year >= 2014)
) AS X
PIVOT
(   
    SUM(NetValue) 
    FOR Years IN ([2014], [2015])
) AS Y

我没有太多运气 - 有没有人对更好的方法有任何建议或想法?

提前致谢!

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select ACM.CustomerName,
       sum(case when IG.Year = 2014 and FY = 'FY' then value else 0 end) as 2014_YTD_FY,
       sum(case when IG.Year = 2014 then value else 0 end) as 2014_YTD,
       sum(case when IG.Year = 2015 and FY = 'FY' then value else 0 end) as 2015_YTD_FY,
from Invoice IG join
     AccountCustomer ACM
     on IG.AccountNumber = ACM.AccountNumber
where IG.Year >= 2014
group by ACM.CustomerName and YTD = 'YTD';