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

请问一个sql语句
已知下表,要把相同orderNo的qty相加,结果要显示出所有的字段,
列如得出a1的结果为:
OrderNo     Qty     Cust     ReqDate           Price         OrigAMT    
a1     112     c04n       2007-09-06       143.95       34871.68    
注:除OrderNo与Qty字段,其他字段的数据如有多条,只取第一条对应的记录
   
OrderNo     Qty     Cust     ReqDate           Price         OrigAMT    
--------------------------------------------------   --------
a1       32     C04N           2007-09-06       143.95       34871.68        
a1       80     C04N           2007-09-06       176.81       107076.8        
a2       176 C04N           2007-09-04       163.71       218120.32      
a3       32   C04N           2007-09-05       165.18       40013.76        
a3       32   C04N           2007-09-05       176.81       42830.72          
a4       96   C04N           2007-09-06       143.95       104615.04      
a4       80   C04N           2007-09-07       176.4         107076.8

------解决方案--------------------
--创建环境
create table #tbl
(OrderNo varchar(20),Qty int, Cust varchar(20),ReqDate Datetime,Price numeric ,OrigAMT numeric)
insert into #tbl select 'a1 ' ,32, 'C04N ', '2007-09-06 ',143.95,34871.68
union select 'a1 ' ,80, 'C04N ', '2007-09-06 ',176.81,107076.8
union select 'a2 ' ,176, 'C04N ', '2007-09-04 ',163.71,218120.32
union select 'a3 ' ,32, 'C04N ', '2007-09-05 ',165.18,40013.76
union select 'a3 ' ,32, 'C04N ', '2007-09-05 ',176.81,42830.72
union select 'a4 ' ,96, 'C04N ', '2007-09-06 ',143.95,104615.04
union select 'a4 ' ,80, 'C04N ', '2007-09-07 ',176.4,107076.8

--查询SQL

select id=identity(int,1,1),* into #t from #tbl
select b.OrderNo,b.Qty,Cust,ReqDate,Price,OrigAMT from #t t
left join
(
select OrderNo,sum(Qty)as Qty from #tbl
group by OrderNo having count(OrderNo)> =1
) as b
on t.OrderNo=b.OrderNo
where not exists
(select 1 from #t where id <t.id and OrderNo=t.OrderNo)