在SQL Server中使用group by的列名的总和?

时间:2014-01-28 06:29:50

标签: sql sql-server-2008 stored-procedures aggregate-functions

ALTER PROCEDURE [dbo].[K_RT_GetProdutstogrid]
@purchasedby int

AS
BEGIN

SET NOCOUNT ON;

 select PS.sno, PD.productname,sum(PS.quantity) as quantity,PS.modelno from   K_RT_PurchaseDet PS 
 inner join K_RT_ProductDetails PD on PD.sno=PS.product 
 where purchasedby=@purchasedby and PS.quantity!=0 and attrited='false'

 group by  PD.productname,PS.modelno,PS.company,PS.sno

END

通过这个我出去了

sno    product   stock   modelno
1      Computer   2       Dell
2      Mobile     3       Nokia7100
3      Mobile     2       Nokia7100

但实际上我想把它作为

sno   product    stock    modelno 
1      Computer   2       Dell
2      Mobile     5       Nokia7100

我是这样写的,但我没有得到请帮助我......

2 个答案:

答案 0 :(得分:1)

只需在查询中编辑group by子句即可。成为

group by PD.productname,PS.modelno

答案 1 :(得分:1)

查询:

SELECT MIN(PS.sno) AS sno, 
       PD.productname,
       SUM(PS.quantity) as quantity,
       PS.modelno 
FROM K_RT_PurchaseDet PS 
 JOIN K_RT_ProductDetails PD on PD.sno=PS.product 
 WHERE purchasedby=@purchasedby 
  AND PS.quantity!=0 and attrited='false'
GROUP BY PD.productname,
         PS.modelno,
         PS.company