[英]Decide the output if a value exists in the group after SQL grouping
id、number、user 和 status 是我的列在這里, “status”列的枚舉值是'A'、'D'、'P' 和 'R'
SELECT
number,
count(user),
status
FROM
table1
GROUP BY
number
ORDER BY
id DESC
我正在對“數字”列中的結果進行分組,如果該組的任何記錄包含“狀態”的“ P ”,則結果必須是“P” ,否則結果必須是按字母順序排列的最大值
您可以使用條件聚合來做到這一點:
SELECT number,
COUNT(user) counter,
COALESCE(MAX(CASE WHEN status = 'P' THEN status END), MAX(status)) status
FROM table1
GROUP BY number
如果特定number
的任何status
值是'P'
則MAX(CASE WHEN status = 'P' THEN status END)
將返回'P'
,如果它們都不是'P'
,它將返回NULL
。
所以COALESCE()
將在第一種情況下返回'P'
或在第二種情況下返回MAX(status)
。
如果存在'P'
,則計算輔助值持有信息,然后由該值決定:
SELECT
case
when sum(case when status = 'P' then 1 else 0 end) > 0 then 'P'
else max(status)
end,
number
FROM
table1
GROUP BY
number
請 state 您的數據庫供應商。 例如,在 Postgres 的情況下,也可以使用count(*) filter (where...)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.