日期:2014-05-18  浏览次数:20566 次

关于数据库统计报表的问题
现有
表A
ID AccountName CarCode
-----------------------------------
1 重型汽车 1101,1102,1103,1104
2 中型汽车 1105,1106,1107,1108
3 轻型汽车 1109,1110,1111,1112

表B
ID CarCode CarName SalePrice SaleNum Company
-----------------------------------------------
1 1101 东风101 85000 5 公司1
2 1102 跃进102 96000 3 公司2
3 1103 东风103 120000 2 公司1
4 1104 跃进104 135000 1 公司3
5 1105 长安101 84000 4 公司1
6 1106 长安102 97000 3 公司2
7 1107 北京101 78000 7 公司3  
8 1108 北京102 86000 5 公司2
9 1109 奇瑞101 28000 4 公司1
10 1110 奇瑞102 34000 6 公司3
11 1111 吉利101 25000 3 公司1
12 1112 吉利102 33000 4 公司2

现要得到如下统计结果: 
序号 重型汽车 中型汽车 轻型汽车
公司1 665000 336000 187000
公司2 288000 721000 132000
公司3 135000 546000 204000

请问查询语句该怎么写??

------解决方案--------------------
Create table A
(id int identity,AccountName varchar(10),carcode varchar(30))


insert into a select '重型汽车' , '1101,1102,1103,1104' 
insert into a select '中型汽车' , '1105,1106,1107,1108' 
insert into a select '轻型汽车' , '1109,1110,1111,1112' 

create table B
(id int ,carcode varchar(10),carname varchar(10),saleprice int,salenum int,company varchar(10))
insert into b select 1 ,'1101', '东风101', 85000 , 5 , '公司1' 
insert into b select 2 ,'1102', '跃进102', 96000 , 3 , '公司2' 
insert into b select 3 ,'1103', '东风103', 120000 , 2 , '公司1' 
insert into b select 4 ,'1104', '跃进104', 135000 , 1 , '公司3' 
insert into b select 5 ,'1105', '长安101', 84000 , 4 , '公司1' 
insert into b select 6 ,'1106', '长安102', 97000 , 3 , '公司2' 
insert into b select 7 ,'1107', '北京101', 78000 , 7 , '公司3'
insert into b select 8 ,'1108', '北京102', 86000 , 5 , '公司2' 
insert into b select 9 ,'1109', '奇瑞101', 28000 , 4 , '公司1' 
insert into b select 10 ,'1110', '奇瑞102', 34000 , 6 , '公司3' 
insert into b select 11 ,'1111', '吉利101', 25000 , 3 , '公司1' 
insert into b select 12 ,'1112', '吉利102', 33000 , 4 , '公司2' 

create view c 
as
select a.accountname,saleprice,salenum,company from a ,b
where Charindex(b.carcode,a.carcode)>0

select * from c

declare @sql varchar(1000)
set @sql='select company '
select @sql=@sql+',sum(case when accountname='''+accountname+''' then salenum*saleprice else 0 end) as '+accountname
from (select distinct accountname from c ) a
set @sql=@sql+' from c group by company'
exec(@sql)

company 轻型汽车 中型汽车 重型汽车
---------- ----------- ----------- -----------
公司1 187000 336000 665000
公司2 132000 721000 288000
公司3 204000 546000 135000

(3 行受影响)
------解决方案--------------------
试写一下,
declare @a char(100),@b char(100),@c char(100),@d char(100),@e char(100),@f char(100),@g char(100),@h char(100),@i char(100)
select @a= sum(saleprice * salenum) from B where company='公司1' and carcode in ('1101','1102','1103','1104')
select @b= sum(saleprice * salenum) from B where company='公司1' and carcode in ('1105','1106','1107','1108')
select @c= sum(saleprice * salenum) from B where company='公司1' and carcode in ('1109','1110','11011','1112')
select @d= sum(saleprice * salenum) from B where company='公司2' and carcode in ('1