简体   繁体   中英

SQL multiple sums in one query

I am trying to learn SQL and am wondering how to write this query for multiple dates. I tried using CASE but it is not outputting the correct totals. This query works.

I am trying to total the dailyrate for each reservation which is the effectively the daily sales.

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

This was my attempt using CASE but it does not produce the correct totals.

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       |  
+------------------+------------------+----------+-

Are you looking for the COUNT of each daily_rate on each day? If so, this may be the query you're after:

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;

If you're looking for the SUM of the daily rates for each table, then this query may work for you:

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;

I think you were missing the GROUP BY, as both the SUM and COUNT functions are aggregate functions and need a GROUP BY to show the correct data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM