2014-09-21 46 views
1

我执行子查询来识别我想要的行排除。那些是在列b上有NULL值的那些。 Parent Supplier Name。这工作正常,直到我试图得到其余的总和(b。Spend Value in LC)。LEFT JOIN和IS NULL工作但不是SUM功能

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 
.... 
.... 

谢谢!

+0

显示一些示例数据。 – Laurence 2014-09-21 22:24:31

+0

你可以试着'Sum(Coalesce(b。\'花在LC \'中的值,0))' – Siyual 2014-09-21 23:03:06

回答

0

像你之前这么多的人,你已经受骗MySQL的非标准分组支持...

确保所有的非聚集列的group by条款中列出:

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

尽管如果你试过你查询其他数据库将rause SQL异常,MySQL允许你省略非聚集colums,在这种情况下,它返回一个单排随机(作为实用性的问题,它返回行)作为编码的每个唯一组。

+0

感谢您的回复。我试过'GROUP BY a.'BW Parent Number',a.'Vendor Name';并且 ; ''GROUP BY a.'BW家长Number',a.'Vendor Name',b.'Parent供应商Name',b.'Child供应商ID'',没有sucess。我知道这些行在LC上有b.'Spend Value的实际值。有任何建议吗? – nangys 2014-09-22 00:04:52