我有以下 SQL
SELECT a.id ,
a.name,
COUNT( se.end_date )
FROM accounts a
INNER JOIN items it
ON it.account_id = a.id
INNER JOIN schedule_elements se
ON it.id = se.item_id
WHERE se.end_date >= '2022.04.04'
GROUP BY a.id,
a.name;
這僅回傳通過 where 子句的行 (275)。我需要回傳所有帳戶(2297),但我只想在 end_date 是今天或更大時顯示計數。
我試過這個:
SELECT a.id ,
a.name,
IF( se.end_date >= '2022.04.04', COUNT( se.end_date ), ' 0 ')
FROM accounts a
INNER JOIN items it
ON it.account_id = a.id
INNER JOIN schedule_elements se
ON it.id = se.item_id
GROUP BY a.id ,
a.name;
因為我認為如果它大于第 4 個或 0 如果不是,它會將計數放入。但是當我運行它時,我得到以下資訊。
#42000Expression #3 of SELECT list is not in GROUP BY clause and
contains nonaggregated column 'se.end_date' which is not functionally dependent
on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
谷歌搜索錯誤似乎我可以關閉它,但我無法對資料庫進行任何更改,所以我認為這是不可能的。
uj5u.com熱心網友回復:
您應該將條件附在里面COUNT():
COUNT(CASE WHEN se.end_date >= '2022-04-04' THEN 1 END)
或者,使用SUM():
SUM(se.end_date >= '2022-04-04')
要么:
COALESCE(SUM(se.end_date >= '2022-04-04'), 0)
以防萬一end_date.
如果您確實想要始終使用當前日期,請使用CURRENT_DATE而不是'2022-04-04'.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/456408.html
