[英]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.