[英]How to filter query in SQL conditionally?
我有一個查詢顯示每個 shop_id 和國家/地區的收入,如下所示。
select shop_id,
country,
start_date,
sum(earnings) as earnings
from x
where country IN ('DE', 'IT', 'ES')
group by 1,2,3
但是,我想在國家DE只有三個商店,而在國家rest的所有商店。
shop_id IN ('1', '2', '3')
我怎樣才能做到這一點?
聽起來您的條件可以使用一些嵌套,如下所示:
select shop_id,
country,
start_date,
sum(earnings) as earnings
from x
where country IN ('IT', 'ES')
OR (country = 'DE' AND sop_id IN ('1','2','3'))
group by 1,2,3
您可以在WHERE
子句中添加一個CASE
語句,該語句檢查country
列中的 DE 並僅返回指定的三個shop_id
,否則返回shop_id
。
WHERE
CASE
WHEN country = 'DE' AND shop_id IN ('1', '2', '3') THEN 1
WHEN country IN ('IT', 'ES') THEN 1
ELSE 0
END = 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.