sql中如何使用语句

来源:百度知道 编辑:UC知道 时间:2024/06/20 07:34:05
我有一个表,xssj
unitcode operator money type
1 小文 2400 团购
2 小李 3400 经销
3 小文 1200 经销
5 小李 3500 团购
9 小王 4900 名烟名酒店
12 小刘 1200 团购
14 小文 5000 批发
19 小文 9000 团购
.. .. .. ..

通过sql语句实现效果
operator 团购 经销 名烟名酒 批发 合计
小文 11400 1200 0 5000 17600
小李 3500 3400 0 0 6900
小王 0 0 4900 0 4900
小刘 1200 0 0 0 1200

查询语句该怎么写?
谢谢两位哈,可是type有很多数据啊,必须一个一个的列出来吗?不能自动开成吗?因为我还有一个表就是专门的类型表,随着业务开展type的数值就越多,不是每新添加个值的话(如:夜场)我都要改查询语句吗?

怎么写啊?

use Tempdb
go
--> -->

if not object_id('xssj') is null
drop table xssj
Go
Create table xssj([unitcode] int,[operator] nvarchar(2),[money] int,[type] nvarchar(5))
Insert xssj
select 1,N'小文',2400,N'团购' union all
select 2,N'小李',3400,N'经销' union all
select 3,N'小文',1200,N'经销' union all
select 5,N'小李',3500,N'团购' union all
select 9,N'小王',4900,N'名烟名酒店' union all
select 12,N'小刘',1200,N'团购' union all
select 14,N'小文',5000,N'批发' union all
select 19,N'小文',9000,N'团购'
Go
Select [operator],
[团购]=sum(case when [type]=N'团购' then [money] else 0 end),
[经销]=sum(case when [type]=N'经销' then [money] else 0 end),
[批发]=sum(case when [type]=N'批发' then [money] else 0 end),
[合计]=sum([money])
from xssj group by [operator]