SQL在一个查询中多个和

时间:2018-07-17 22:16:29

标签: mysql sql mariadb

我正在尝试学习SQL,并且想知道如何针对多个日期编写此查询。我尝试使用CASE,但未输出正确的总数。该查询有效。

我正在尝试对每个预订的日费率进行总计,这实际上是日销售额。

SELECT SUM(dailyrate) AS 1June
FROM reservations
    WHERE start_date < '2018-06-02' AND end_date > '2018-06-01';

这是我使用CASE进行的尝试,但无法得出正确的总数。

select dailyrate, 
    sum(case when start_date < '2018-06-02' AND end_date > '2018-06-01' then 1 else 0 end) as 1june,
    sum(case when start_date < '2018-06-03' AND end_date > '2018-06-02' then 1 else 0 end) as 2june,
    sum(case when start_date < '2018-06-04' AND end_date > '2018-06-03' then 1 else 0 end) as 3june
FROM reservations;

+------------------+------------------+----------+-
|   start_date     |    end_date      | dailyrate |
+------------------+------------------+----------+--
| 2018-06-01 05:00 | 2018-06-01 15:00 | 22       |  
| 2018-05-21 05:00 | 2018-06-04 19:00 | 11.5     |  
| 2018-06-01 15:00 | 2018-06-07 05:00 | 24       |  
| 2018-06-03 05:00 | 2018-06-02 22:00 | 9.5      | 
| 2018-05-21 12:00 | 2018-06-11 05:00 | 31       |  
+------------------+------------------+----------+-

1 个答案:

答案 0 :(得分:0)

您是否正在寻找每一天的day_rate的COUNT个? 如果是这样,这可能是您要执行的查询:

SELECT dailyrate, 
COUNT(CASE WHEN start_date < '2018-06-02' AND end_date > '2018-06-01' THEN 1 ELSE 0 end) AS 1june,
COUNT(CASE WHEN start_date < '2018-06-03' AND end_date > '2018-06-02' THEN 1 ELSE 0 end) AS 2june,
COUNT(CASE WHEN start_date < '2018-06-04' AND end_date > '2018-06-03' THEN 1 ELSE 0 end) AS 3june
FROM reservations
GROUP BY dailyrate;

如果您要查找每个表的每日费率的总和,则此查询可能对您有用:

SELECT dailyrate, 
SUM(CASE WHEN start_date < '2018-06-02' AND end_date > '2018-06-01' THEN dailyrate ELSE 0 end) AS 1june,
SUM(CASE WHEN start_date < '2018-06-03' AND end_date > '2018-06-02' THEN dailyrate ELSE 0 end) AS 2june,
SUM(CASE WHEN start_date < '2018-06-04' AND end_date > '2018-06-03' THEN dailyrate ELSE 0 end) AS 3june
SUM reservations
GROUP BY dailyrate;

我认为您缺少GROUP BY,因为SUM和COUNT函数都是聚合函数,需要GROUP BY才能显示正确的数据。