我正在处理一个带有“ 2015年费用”,“ 2015年收入”,“ 2016年费用”,“ 2016年收入”等列的单个仓库表。我需要将它们分成“收入”,“费用” ,然后对“结算年份”进行一些分析。许多记录都有多年的收费和收入。
我尝试过的CASE语句仅在第一年生效,但我需要在所有年份都生效。
这是我的案件陈述:
(CASE when 2015_revenue IS NOT NULL then 2015_revenue
when 2016_revenue_$ IS NOT NULL then 2016_revenue
END) as revenue,
(CASE when 2015_fee IS NOT NULL then 2015_fee
when 2016_fee IS NOT NULL then 2016_fee
END) as fee,
(CASE when 2015_revenue IS NOT NULL then '2015'
when 2015_fee IS NOT NULL then '2015'
when 2016_revenue IS NOT NULL then '2016'
when 2016_fee IS NOT NULL then '2016'
end) as bill_year
有什么想法吗?
答案 0 :(得分:0)
这不是CASE语句,它正在创建带有UNION的临时表并加入该表:
SELECT p1.[bunch of fields from table]
amts.fee
amts.revenue
amts.bill_year
FROM table p1
JOIN (SELECT id, 2015_revenue as revenue, 2015_fee as fee, '2015' as bill_year FROM table
UNION
SELECT id, 2016_revenue as revenue, 2016_fee as fee, '2016' as bill_year FROM table
U) amts on amts.id = p1.id;