2014-07-17 80 views
0

我有一個漂亮的平坦表 - tbl_values其中有userids以及netAmounts在給定的行。在以下示例中,根據時間戳,2280在過去30天內沒有記錄。collesce問題與mysql

我希望這會返回3行,2280爲「0」 - 但我只得到2回?我在這裏錯過了很明顯的東西嗎

SELECT userid, (COALESCE(SUM(netAmount),0)) as Sum FROM `tbl_values` where userid in (2280, 399, 2282) and date > (select DATE_SUB(NOW(), INTERVAL 30 day)) GROUP BY userid 

回答

1

假設你總是希望返回用戶,不管他們寧可在tbl_values匹配的記錄,你要找什麼是outer join

SELECT u.userid, COALESCE(SUM(v.netAmount),0) as Sum 
FROM (
    SELECT 2280 userid UNION ALL 
    SELECT 399 UNION ALL 
    SELECT 2282 
) u 
    LEFT JOIN `tbl_values` v ON u.userid = v.userid AND 
     v.date > DATE_SUB(NOW(), INTERVAL 30 day) 
GROUP BY u.userid 

如果你也許有一個Users表,那麼你可以用它代替子查詢。

SELECT u.userid, COALESCE(SUM(v.netAmount),0) as Sum 
FROM users u 
    LEFT JOIN `tbl_values` v ON u.userid = v.userid AND 
     v.date > DATE_SUB(NOW(), INTERVAL 30 day) 
WHERE u.userid in (2280, 399, 2282) 
GROUP BY u.userid 
+0

第二個查詢周赫然。如果我想要'0'而不是Null,那麼我認爲我仍然可以用case語句來做到這一點? – timw07

+0

這工作完美... SELECT u.userid,COALESCE(SUM(v.netAmount),0)as Sum FROM tbl_user u LEFT JOIN'tbl_values' v ON u.userid = v.userid AND v.date> DATE_SUB(NOW(),INTERVAL 30天) 其中u.userid在(2280,399,2282) GROUP BY u.userid ORDER BY u.userid – timw07

+0

@ timw07 - 很高興能幫到你!我編輯了這個回覆,因爲它看起來像你想要的'合併'一樣。 – sgeddes

0

這是您的查詢:

SELECT userid, (COALESCE(SUM(netAmount),0)) as Sum 
FROM `tbl_values` 
where userid in (2280, 399, 2282) and 
     date > (select DATE_SUB(NOW(), INTERVAL 30 day)) 
GROUP BY userid; 

where子句中的過濾器找到匹配的用戶ID 2280是假設至少有一行的某處存在任何行,你可以得到你想要的東西通過移動date比較條件聚合:

SELECT userid, 
     sum(case when date > DATE_SUB(NOW(), INTERVAL 30 day) 
       then netAmount else 0 
      end) as Sum 
FROM `tbl_values` 
WHERE userid in (2280, 399, 2282) 
GROUP BY userid; 

編輯:

如果你真的希望所有的三個結果,然後用left join

SELECT u.userid, 
     coalesce(sum(netAmount), 0) as Sum 
FROM (select 2280 as userid union all 
     select 399 union all 
     select 2282 
    ) u left join 
     tbl_values t 
     on u.userid = t.userid and 
     t.date > DATE_SUB(NOW(), INTERVAL 30 day) 
GROUP BY u.userid; 
+0

有趣的是,這仍然只是讓我2個結果現在 - 但有一組0適當的2280,我進一步深挖,可能是很簡單的東西:) – timw07