表TABLE1:
x_ID x_sale x_date
A 200 2009-12-01
B 300 2009-12-01
A 100 2009-12-02
C 70 2009-12-02
B 50 2009-12-03
A 150 2009-12-03
要求查询01号到03号A的总x_sale,B的总x_sale,C的总x_sale,还有01号到03号所有的总和,正确的sql要怎么写,
我现在用group by 求出分开的总数,
Select TABLE1.x_ID,SUM(TABLE1.x_sale) AS sumsalein FROM WHERE (TABLE1.x_date BETWEEN '"&2009-12-01
&"' AND '"&2009-12-03&"') GROUP BY TABLE1.x_ID,
想得到如下效果:
x_ID x_sale
A 450
B 350
C 70
总和 870(这个总和从何而来)
一条语句可以求出来吗?还是要分开执行?(用的是sqlsever2000)
这样可以求出A的总x_sale,B的总x_sale,C的总x_sale,但是还是一个总数SUM(A+B+C)要怎么体现出来,怎么写呢??
------解决方案--------------------
- SQL code
select x_id=isnull(x_id,'总和'),x_sale=sum(x_sale) from [table1] where x_date between '2009-12-01' and '2009-12-03'group by x_id with rollup
------解决方案--------------------
- SQL code
--> 测试数据: [table1]if object_id('[table1]') is not null drop table [table1]create table [table1] (x_ID varchar(10),x_sale int,x_date datetime)insert into [table1]select 'A',200,'2009-12-01' union allselect 'B',300,'2009-12-01' union allselect 'A',100,'2009-12-02' union allselect 'C',70,'2009-12-02' union allselect 'B',50,'2009-12-03' union allselect 'A',150,'2009-12-03'select x_id=isnull(x_id,'总和'),x_sale=sum(x_sale) from [table1] where x_date between '2009-12-01' and '2009-12-03'group by x_id with rollup--结果:x_id x_sale---------- -----------A 450B 350C 70总和 870
------解决方案--------------------
Select TABLE1.x_ID,SUM(TABLE1.x_sale) AS sumsalein FROM WHERE (TABLE1.x_date BETWEEN '"&2009-12-01
&"' AND '"&2009-12-03&"') GROUP BY TABLE1.x_ID
union all
Select '总和',SUM(TABLE1.x_sale) AS sumsalein FROM WHERE (TABLE1.x_date BETWEEN '"&2009-12-01
&"' AND '"&2009-12-03&"')
===============
加个union all 就行了