将sql语句中列值,转变成行的值,同时要求求和,汇总,超难
CREATE TABLE [dbo].[temp1] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[depart] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[autonumber] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[type] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[money] [decimal](18, 2) NULL ,
[inputdate] [datetime] NULL
) ON [PRIMARY]
insert temp1
select '财务部 ', '津A 12345 ', '油费 ',100, '2007-5-11 ' union
select '财务部 ', '津A 12345 ', '高速费 ',80, '2007-5-11 ' union
select '办公室 ', '津A 54321 ', '维修费 ',60, '2007-5-11 ' union
select '办公室 ', '津A 54321 ', '存车费 ',70, '2007-5-11 ' union
select '财务部 ', '津A 12345 ', '油费 ',90, '2007-5-25 ' union
select '办公室 ', '津A 54321 ', '油费 ',120, '2007-5-25 '
想要的结果是
depart autonumber,油费,高速费,维修费,存车费
财务部 津A 12345 190 80 0 0
办公室 津A 54321 120 0 60 70
即:车牌号没有重复的记录,且对各项费用进行求和,同时还将列变为行
那位好心人,帮忙看看,谢谢!!!!!!!!!!!!!!!!
------解决方案--------------------select depart,autonumber,sum(case when type= '油费 ' then money else 0 end)as 油费,
sum(case when type= '高速费 'then money else 0 end)as 高速费,
sum(case when type= '维修费 'then money else 0 end)as 维修费,
sum(case when type= '存车费 'then money else 0 end)as 存车费
from temp1
group by depart,autonumber
depart autonumber 油费 高速费 维修费 存车费
-------------------------------------------------- -------------------------------------------------- ---------------------------------------- ---------------------------------------- ---------------------------------------- ----------------------------------------
财务部 津A 12345 190.00 80.00 .00 .00
办公室 津A 54321 120.00 .00 60.00 70.00
(所影响的行数为 2 行)