mysql - 聚合函数的过滤子句

标签 mysql sql

我的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)。您只需在 selectgroup by 子句中使用 deliverydate 即可。这使得将查询扩展到多个月变得更容易。如果有时间组件,请使用 date() 而不是 day()

如果您有很多其他付款选项,那么将 and payment_option in ('EBS', 'COD') 添加到 where 子句也可能有助于提高性能。

关于mysql - 聚合函数的过滤子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59225464/

相关文章:

php - 显示来自 mysql 列的计数值?

Javascript 时间戳转 php - mysql 时间戳类型

php - 将标题转换为十进制后,Wordpress 按 post_title 发布顺序?

sql - 如何删除 SQL 中的重复行(Clickhouse)?

php - 主机名可以注入(inject)SQL吗?

mysql - 来自不同表的子查询最后日期/值

mysql - Cassandra 还是 MySQL/PostgreSQL?

mysql - SQL 选择投资组合中的持股集中度

sql - 无效的列名?

sql - 在配置单元 SQL 中聚合点击流数据(组中的第一个值)CTE SQL