這是您的查詢:
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'而不是Null,那麼我認爲我仍然可以用case語句來做到這一點? – timw07
這工作完美... 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
@ timw07 - 很高興能幫到你!我編輯了這個回覆,因爲它看起來像你想要的'合併'一樣。 – sgeddes