【问题标题】:LEFT JOIN and IS NULL working but not the SUM functionLEFT JOIN 和 IS NULL 工作但不是 SUM 函数
【发布时间】:2014-09-21 22:19:44
【问题描述】:

我执行子查询来识别我想要排除的行。这些是在 b.Parent Supplier Name 列上具有 NULL 值的那些。在我尝试得到其余部分的总和(b.Spend Value in LC)之前,这很好用。

SELECT a.`BW Parent Number` , a.`Vendor Name` , b.`Parent Supplier Name` , sum( b.`Spend Value in LC` ) as sum
FROM scrubs a
LEFT JOIN (

    SELECT `Child Supplier ID` , `Parent Supplier Name` , `Spend Value in LC` 
    FROM pdwspend
    WHERE `BU ID` = 'BU_1'
    AND `version` LIKE '%FINAL%'
 )b ON a.`BW Parent Number` = b.`Child Supplier ID` 

WHERE a.`year` =2014
AND b.`Parent Supplier Name` IS NULL 
GROUP BY a.`BW Parent Number` 
ORDER BY sum( b.`Spend Value in LC` ) DESC

结果欲望有这样的结构:

`BW Parent Number` | `Vendor Name` | `Parent Supplier Name` | sum
 BW0001               XYC                 NULL                300,000
 .....
 .....

现在我得到了所有不包括在子查询中的行:

`BW Parent Number` | `Vendor Name` | `Parent Supplier Name` | sum
 BW0001               XYC                 NULL                NULL
 ....
 ....

谢谢!

【问题讨论】:

  • 显示一些示例数据。
  • 你可以试试Sum(Coalesce(b.`Spend Value in LC`, 0))

标签: mysql sql sum left-join isnull


【解决方案1】:

像您之前的许多其他人一样,您已成为 mysql 非标准分组支持的牺牲品...

确保所有非聚合列都列在group by 子句中:

...
GROUP BY a.`BW Parent Number`, a.`Vendor Name`
...

虽然其他数据库在您尝试查询时会引发 SQL 异常,但 Mysql 允许您省略非聚合列,在这种情况下,它会返回 单个随机行(出于实用性考虑,它返回 first 行)为每个唯一组编码。

【讨论】:

  • 感谢您的回复。我试过GROUP BY a.BW Parent Number, a.Vendor Name`;并且 ; GROUP BY a.`BW Parent Number`, a.`Vendor Name` , b.`Parent Supplier Name` , b.`Child Supplier ID,没有成功。我知道这些行在 b.Spend Value in LC 上有实际值。有什么建议吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-13
  • 2021-11-29
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 2021-01-30
相关资源
最近更新 更多