我的sql语法似乎有错误。这是我正在运行的命令:
select day(deliverydate),
sum(total_amount) FILTER (WHERE payment_option='EBS'),
sum(total_amount) FILTER (WHERE payment_option='COD')
from orders
where month(deliverydate)=2 and
year(deliverydate)=2019
group by day(deliverydate)
order by 1;
有没有更好的方法来输出: the nos will be from data obviously
非常感谢任何帮助。
最佳答案
我建议将其写为:
select day(deliverydate),
sum(case when payment_option = 'EBS' then total_amount end),
sum(case when payment_option = 'COD' then total_amount end)
from orders
where deliverydate >= '2019-02-01' and
deliverydate < '2019-03-01'
group by day(deliverydate)
order by 1;
请注意日期逻辑的更改。这使得 where
子句对索引更加友好。
此外,如果 deliverydate
没有时间部分,则不需要 day(deliverydate)
。您只需在 select
和 group by
子句中使用 deliverydate
即可。这使得将查询扩展到多个月变得更容易。如果有时间组件,请使用 date()
而不是 day()
。
如果您有很多其他付款选项,那么将 and payment_option in ('EBS', 'COD')
添加到 where
子句也可能有助于提高性能。
关于mysql - 聚合函数的过滤子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59225464/