【问题标题】:sum of column name using group by in SQL server?在 SQL Server 中使用 group by 的列名总和?
【发布时间】:2014-02-19 07:53:57
【问题描述】:
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

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

【问题讨论】:

  • 您真的希望sno 被错误地报告为 2 个诺基亚 7100s 吗?如果是这样,显示哪个sno 值是否重要?如果您实际上不需要sno,那么解决方案很简单 - 请参阅下面的@Akshay 答案。

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


【解决方案1】:

只需在查询中编辑group by 子句。做到这一点

group by PD.productname,PS.modelno

【讨论】:

  • 并从select 中删除PS.sno,否则SQL Server 会报错。
【解决方案2】:

查询:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多