22,301
社区成员




WITH table1(Com_Budget_subjects_code,Com_Budget_subjects_title,Com_Budget_subjects_type,YEARS,YSPrice,SJPrice) AS (
SELECT 660101,'工资','固定费用',2014,100,0 UNION ALL
SELECT 660101,'工资','固定费用',2015,1100,307 UNION ALL
SELECT 660102,'奖金','变动费用',2014,200,0 UNION ALL
SELECT 660102,'奖金','变动费用',2015,2200,608
)
select Com_Budget_subjects_code,Com_Budget_subjects_title,Com_Budget_subjects_type,
max(case YEARS when '2014' then YSPrice else 0 end) '2014YSPrice',
max(case YEARS when '2014' then SJPrice else 0 end) '2014SJPrice',
max(case YEARS when '2015' then YSPrice else 0 end) '2015YSPrice',
max(case YEARS when '2015' then SJPrice else 0 end) '2015SJPrice'
from table1
group by Com_Budget_subjects_code,Com_Budget_subjects_title,Com_Budget_subjects_type order by Com_Budget_subjects_code
WITH
/* 测试数据
table1(Com_Budget_subjects_code,Com_Budget_subjects_title,Com_Budget_subjects_type,YEARS,YSPrice,SJPrice)AS(
SELECT 660101,'工资','固定费用',2014,100,0 UNION ALL
SELECT 660101,'工资','固定费用',2015,1100,307 UNION ALL
SELECT 660102,'奖金','变动费用',2014,200,0 UNION ALL
SELECT 660102,'奖金','变动费用',2015,2200,608
),*/
a AS (
SELECT Com_Budget_subjects_code,
Com_Budget_subjects_title,
Com_Budget_subjects_type,
CONVERT(varchar(11),YEARS)+'YSPrice' AS Item,
YSPrice AS Price
FROM table1
UNION ALL
SELECT Com_Budget_subjects_code,
Com_Budget_subjects_title,
Com_Budget_subjects_type,
CONVERT(varchar(11),YEARS)+'SJPrice' AS Item,
SJPrice AS Price
FROM table1
)
SELECT *
FROM a
PIVOT (SUM(Price) FOR
Item IN ([2014YSPrice], [2014SJPrice],
[2015YSPrice], [2015SJPrice])
) P
Com_Budget_subjects_code Com_Budget_subjects_title Com_Budget_subjects_type 2014YSPrice 2014SJPrice 2015YSPrice 2015SJPrice
------------------------ ------------------------- ------------------------ ----------- ----------- ----------- -----------
660101 工资 固定费用 100 0 1100 307
660102 奖金 变动费用 200 0 2200 608
;with cte(code, title, [types], [years], yjprice, sjprice) as
(
select '660101','工资','固定费用','2014',100,0 union all
select '660101','工资','固定费用','2015',1100,307 union all
select '660102','奖金','变动费用','2014',200,0 union all
select '660102','奖金','变动费用','2015',2200,608
)
select a.code, a.title, a.[types],
a.[2014yj], a.[2014sj],
b.[2015yj], b.[2015sj]
from
(
select code, title, [types], yjprice as [2014yj], sjprice as [2014sj]
from cte where years = '2014'
) as a
inner join
(
select code, yjprice as [2015yj], sjprice as [2015sj]
from cte where years = '2015'
) as b
on a.code = b.code