日期:2014-05-17  浏览次数:20449 次

SQL的筛选,怎么筛选下面这种情况,请SQL高手指导!
表的内容如下:

货号 名称 批号 数量  
1 白加黑 20121023 8
1 白加黑 20110630 50
1 白加黑 20100326 2
2 银翘片 20120312 100
2 银翘片 20120108 50


请问用什么样的Select语句能筛选成下面的表货号 名称 数量
1 白加黑 60
2 银翘片 150





------解决方案--------------------
SQL code
select 货号,名称,sum(数量) from 表 group by 货号,名称

------解决方案--------------------
SQL code

--> 测试数据:@T
declare @T table([货号] int,[名称] varchar(6),[批号] datetime,[数量] int)
insert @T
select 1,'白加黑','20121023',8 union all
select 1,'白加黑','20110630',50 union all
select 1,'白加黑','20100326',2 union all
select 2,'银翘片','20120312',100 union all
select 2,'银翘片','20120108',50

select [货号],[名称],sum([数量]) as [数量] from @T group by [货号],[名称]
/*
货号          名称     数量
----------- ------ -----------
1           白加黑    60
2           银翘片    150

(2 行受影响)
*/

------解决方案--------------------
SQL code

with t(col1,col2,COL4,col3) as(
select 1,'白加黑','20121023',8 union all
select 1,'白加黑','20110630',50 union all
select 1,'白加黑','20100326',2 union all
select 2,'银翘片','20120312',100 union all
select 2,'银翘片','20120108',50
)
SELECT col1,col2,SUM(col3) AS col FROM t GROUP by col1,col2;

------解决方案--------------------
SQL code
select 货号,名称,sum(数量) as 数量 from 表 group by 货号,名称

------解决方案--------------------
SQL code
select 货号,名称,sum(数量) from 表 group by 货号,名称

------解决方案--------------------
探讨
SQL code

select 货号,名称,sum(数量) from 表 group by 货号,名称