首页 > 解决方案 > 将 2 个不同时间范围的相似查询合并为 1 个,而不是使用 UNION ALL

问题描述

我正在使用 MySQL 5.7,我需要从像这样的表中进行查询

order_id  fee  created_time
111       10    2020-11-16
222       90    2020-11-01
333       300   2000-10-22

结果应该是最近 1 天(昨天)和最近 30 天的总收入,比如

date_range revenue
1            10 
30           400

该专栏date_range是现在之前的最后 X 天,我可以使用“union all”来做到这一点:

SELECT 1 AS date_range, SUM(fee) FROM test 
WHERE created_time >= SUBDATE(CURRENT_DATE, 1) AND created_time < CURRENT_DATE
UNION ALL
SELECT 30 AS date_range, SUM(fee) FROM test 
WHERE created_time >= SUBDATE(CURRENT_DATE, 30) AND created_time < CURRENT_DATE

查询非常相似,是否可以将它们组合成一个查询而不是使用union all


创建表:

CREATE TABLE test (
order_id INT,
fee INT,
created_time DATETIME
)

插入值:

INSERT INTO test VALUES (111,10,'2020-11-16'),(222,90,'2020-11-01'),(333,300,'2020-10-22')

标签: mysqlsql

解决方案


您可以在以下情况下尝试使用案例: https ://dev.mysql.com/doc/refman/5.7/en/case.html

select date_range, sum(fee)
from (
  select
    case 
      when created_time between subdate(current_date, 1) and current_date then 1
      when created_time between subdate(current_date, 30) and current_date then 30
    end case date_range,
    fee
  from test) t
where date_range is not null
group by date_range

推荐阅读