gpt4 book ai didi

mysql - SQL 在一个查询中进行多项求和

转载 作者:行者123 更新时间:2023-11-29 17:18:42 25 4
gpt4 key购买 nike

我正在尝试学习 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 |
+------------------+------------------+----------+-

最佳答案

您是否正在查找每天每个 daily_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 来显示正确的数据。

关于mysql - SQL 在一个查询中进行多项求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51390921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com