首页 > 解决方案 > 如何根据年份将结果分成不同的行?

问题描述

我有一个查询,根据会计年度查看不同商店的利润和运营成本,目前会计年度和变量被分类为单个的相应列,例如:

FiscalYear    Metric    Store    Amount
2017          Profit    A        220
2017          Cost      A        180
2018          Profit    B        200 
2018          Cost      B        300
...

我需要交叉表,以便对于每家商店,我可以比较 2017 年的利润和 2018 年的利润,以及 2017 年的成本和 2018 年的成本。

我通过为 ProfitLossTable 创建 CASE WHEN 语句来分解利润和成本,但我不知道如何让它分别为每个 Store 创建一个“2017 年利润”和“2018 年利润”列。

WITH [Profits, Cost] AS 
(
SELECT ID, StoreID, Number, FYYearID,
CASE WHEN ID = 333 then Number END AS Profit
CASE WHEN ID = 555 then Number END AS Cost
FROM ProfitLossTable
),
Location AS
(
Select StoreID, StoreName
FROM StoreTable
),
FiscalMonth AS
(
SELECT FYYearID, FYYear
FROM FiscalMonthTable
)
SELECT A.Profit, A.Cost
FROM [Profits, Cost] A
JOIN Location B
ON A.StoreID = B.StoreID
JOIN FiscalMonth C
ON A.FYYearID = C.FYYearID

上面的代码显示了这一点,我感觉我已经接近基于年份创建列,但我不知道下一步该做什么。

FiscalYear    Store    Profit    Cost
2017          A        220       100
2017          A        180       100
2018          B        200       100 
2018          B        300       100

标签: ssms

解决方案


作为使用您的数据的工作(无论如何在我的机器上;-p)示例:

create table #temp(
FiscalYear int not null,
Metric nvarchar(50) not null,
Store nvarchar(10) not null,
Amount int not null
)

insert into #temp
values
(2017, N'Profit', N'A', 220),
(2017, N'Cost', N'A', 180),
(2018, N'Profit', N'B', 200),
(2018, N'Cost', N'B', 300)

select * from #temp

select Metric,
[2017] as [2017],
[2018] as [2018]
from (select FiscalYear, Amount, Metric from #temp) base_data
PIVOT
(SUM(Amount) FOR FiscalYear in ([2017], [2018])
) as pvt
order by pvt.Metric

drop table #temp

推荐阅读