SQL使用SUM和INNER JOIN问题

时间:2015-12-28 21:00:30

标签: sql sql-server sql-server-2008

当我尝试执行下面显示的查询时出现此错误

  

列'dbo.Stock_Purchase.Supplier_ID'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

查询:

SELECT  
    dbo.Stock_Purchase.*, dbo.Stock_Purchase_Details.*, 
    dbo.Supplier.*,
    SUM(Stock_Purchase_Details.Discount) AS totaldis
FROM    
    dbo.Stock_Purchase 
INNER JOIN
    dbo.Stock_Purchase_Details ON dbo.Stock_Purchase.Purchase_ID = dbo.Stock_Purchase_Details.Purchase_ID 
INNER JOIN
    dbo.Supplier ON dbo.Stock_Purchase.Supplier_ID = dbo.Supplier.Supplier_ID 
GROUP BY
    Stock_Purchase.Purchase_ID 

1 个答案:

答案 0 :(得分:2)

您只能将GROUP BY中的列包含为"裸" SELECT中的列。所以:

SELECT p.Purchase_ID, sum(pd.Discount) as totaldis
FROM dbo.Stock_Purchase p INNER JOIN
     dbo.Stock_Purchase_Details pd
     ON p.Purchase_ID = pd.Purchase_ID INNER JOIN
     dbo.Supplier s
     ON p.Supplier_ID = s.Supplier_ID
GROUP BY p.Purchase_ID ;

还要注意表别名如何使查询更易于阅读,编写和理解。

如果您确实需要所有细节,可以使用窗口功能:

SELECT p.*, pd.*, s.*,
       SUM(pd.Discount) OVER (PARTITION BY p.Purchase_ID) as totaldis
FROM dbo.Stock_Purchase p INNER JOIN
     dbo.Stock_Purchase_Details pd
     ON p.Purchase_ID = pd.Purchase_ID INNER JOIN
     dbo.Supplier s
     ON p.Supplier_ID = s.Supplier_ID;