使用变量我有这个疑问的case语句MySQL的
select
count(so.shop_order_id),
case
when so.subtotal_amount < 99.99 then 'under 100'
when so.subtotal_amount between 100.00 and 149.99 then '100-149'
when so.subtotal_amount between 150.00 and 249.99 then '150-249'
when so.subtotal_amount between 250.00 and 399.99 then '250-399'
when so.subtotal_amount between 400.00 and 499.99 then '400-499'
when so.subtotal_amount > 500 then '500+'
end
from shop_order so
where so.created_at between '2015-11-29 23:59:59' and '2015-11-31 00:00:01'
and (case
when so.subtotal_amount < 99.99 then 'under 100'
when so.subtotal_amount between 100.00 and 149.99 then '100-149'
when so.subtotal_amount between 150.00 and 249.99 then '150-249'
when so.subtotal_amount between 250.00 and 399.99 then '250-399'
when so.subtotal_amount between 400.00 and 499.99 then '400-499'
when so.subtotal_amount > 500 then '500+'
end) is not null
group by (case
when so.subtotal_amount < 99.99 then 'under 100'
when so.subtotal_amount between 100.00 and 149.99 then '100-149'
when so.subtotal_amount between 150.00 and 249.99 then '150-249'
when so.subtotal_amount between 250.00 and 399.99 then '250-399'
when so.subtotal_amount between 400.00 and 499.99 then '400-499'
when so.subtotal_amount > 500 then '500+'
end)
它很适合我,但我想知道是否有一种方法可以不必重复case语句。我可以设置变量或使用别名或其他东西来代替它吗?每次进行调整时,我都必须编辑案例陈述的每个实例。我对任何事情都很开放。谢谢。
使用MySQL,您可以在GROUP BY中使用SELECT表达式中的别名,但不能在WHERE中使用别名;但是在那个地方使用CASE时,只需做'AND so.subtotal_amount IS NOT NULL'(因为它是唯一的方法,不用担心像99.999那样的值,CASE可能会导致null)_,或者添加' HAVINGAlias IS NOT NULL'到查询中。 ......实际上,在subtotal_amount = 500的逻辑中你有一个“漏洞”。 – Uueerdo
非常好的反馈。谢谢! – Bartonb12