我有一个查询,该查询根据会计年度查看不同商店的利润和运营成本,当前会计年度和变量被归类为单个的相应列,例如:
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语句来细分利润和成本,但是我不知道如何使每个商店分别创建“ 2017 Profit”和“ 2018 Profit”列。
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
答案 0 :(得分:0)
作为使用您的数据的工作示例(无论如何在我的机器上;-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