【问题标题】:TSQL Group By including all columnsTSQL Group By 包括所有列
【发布时间】:2010-12-06 03:29:34
【问题描述】:

我有一个执行如下操作的 TSQL 查询:

SELECT SUM(s.Amount) as TotalSales, p.ProductName
FROM SALES s 
INNER JOIN Product p ON s.ProductID = p.ID
GROUP BY p.ProductName

结果输出是

TotalSales  Product
-----------------------
123.45      Apples
234.56      Oranges
345.67      Grapes

我想做的是获得结果中的所有产品,即使是没有销售的产品。我尝试在产品表上进行 LEFT JOIN,但这只会让事情变得混乱。

所以我希望我的输出是这样的。

TotalSales  Product
-----------------------
123.45      Apples
234.56      Oranges
345.67      Grapes
0.0         Lemons
0.0         Grapefruit

知道怎么做吗?

【问题讨论】:

    标签: sql sql-server tsql aggregate-functions


    【解决方案1】:
    SELECT SUM(ISNULL(s.Amount,0)) as TotalSales, p.ProductName
    FROM SALES s 
    RIGHT JOIN Product p ON s.ProductID = p.ID
    GROUP BY p.ProductName
    

    【讨论】:

    • 使用 RIGHT JOIN 将在输出中显示 NULL PRODUCT.PRODUCTNAME 记录。正确的方法是 LEFT JOIN 到可选表(在这种情况下为SALES)。
    • 顺便说一句,以后当这个查询演变时,尽量不要将LEFT JOINRIGHT JOIN 混用。它会让你发疯!!! (看到我正在使用所有大写字母)
    【解决方案2】:
    SELECT COALESCE(SUM(s.Amount), 0) as TotalSales, p.ProductName
    FROM Product p
    LEFT JOIN SALES s ON s.ProductID = p.ID
    GROUP BY p.ProductName
    

    【讨论】:

    • 我认为您需要将 SUM(s.Amount) 包装在一个合并中以获得“0”
    【解决方案3】:

    左连接(可读性更强):

    SELECT SUM(ISNULL(s.Amount,0)) as TotalSales, p.ProductName
    FROM Product p 
    LEFT JOIN SALES s ON p.ProductID = s.ID
    GROUP BY p.ProductName
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 1970-01-01
      • 2018-04-03
      • 2015-03-26
      • 2014-01-21
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多