如何根据不同的基准获得 MySQL return 多列值?
How to have MySQL return multiple column of values based on a different benchmark?
我有一个 MySQL 数据库 table(销售),其中包含销售数据及其日期。
| Sales ID | Date | Values |
|---------------------------------|
| 1 | 01/01/2020 | 1,500 |
| 2 | 02/01/2020 | 2,000 |
| 3 | 07/02/2020 | 1,000 |
| 4 | 12/03/2020 | 2,000 |
| 5 | 21/06/2020 | 1,000 |
| 6 | 11/08/2020 | 4,200 |
我有一个 SQL 依赖于特定日期基准的查询。
```
SET @benchmark = "31/01/2020";
SELECT SUM(Values) FROM sales
WHERE (date < @benchmark);
```
这个查询应该return只有一个数值。现在我将条件设置为依赖于基准。问题是,我不希望这个基准保持不变。我需要查询 return 从 2020 年 1 月到 2021 年 2 月的每个月底基准的 14 个值。
所以结果可能是这样的,
| SUM(Values) |
|-------------------------------------|
|(result for benchmark = "31/01/2020")|
|(result for benchmark = "29/02/2020")|
|(result for benchmark = "31/03/2020")|
⋮
|(result for benchmark = "31/01/2021")|
|(result for benchmark = "28/02/2021")|
它为每个月底设定了基准。请注意,我无权创建任何内容。
我在考虑一个 while 循环或一个临时的 table,但那些要求我创建总是 returns 的东西“错误代码:1142。创建命令被用户拒绝.. ..”或“错误代码:1044。用户访问被拒绝......”。
感谢任何帮助或反馈。
您可以列出您想要的日期并汇总:
select m.eom, sum(s.sales)
from (select '2020-01-31' as eom union all
select '2020-02-29' union all
. . .
) m left join
sales s
on s.date < m.eom
group by m.eom;
请注意,您还可以使用递归 CTE 或日历生成日期 table。
对于这个特定的查询,您还可以使用累计和:
select last_day(date) as eom, sum(sales),
sum(sum(sales)) over (order by last_day(date))
from sales
group by eom;
这适用于您的特定示例,但可能不适用于其他逻辑。
我有一个 MySQL 数据库 table(销售),其中包含销售数据及其日期。
| Sales ID | Date | Values |
|---------------------------------|
| 1 | 01/01/2020 | 1,500 |
| 2 | 02/01/2020 | 2,000 |
| 3 | 07/02/2020 | 1,000 |
| 4 | 12/03/2020 | 2,000 |
| 5 | 21/06/2020 | 1,000 |
| 6 | 11/08/2020 | 4,200 |
我有一个 SQL 依赖于特定日期基准的查询。
```
SET @benchmark = "31/01/2020";
SELECT SUM(Values) FROM sales
WHERE (date < @benchmark);
```
这个查询应该return只有一个数值。现在我将条件设置为依赖于基准。问题是,我不希望这个基准保持不变。我需要查询 return 从 2020 年 1 月到 2021 年 2 月的每个月底基准的 14 个值。
所以结果可能是这样的,
| SUM(Values) |
|-------------------------------------|
|(result for benchmark = "31/01/2020")|
|(result for benchmark = "29/02/2020")|
|(result for benchmark = "31/03/2020")|
⋮
|(result for benchmark = "31/01/2021")|
|(result for benchmark = "28/02/2021")|
它为每个月底设定了基准。请注意,我无权创建任何内容。
我在考虑一个 while 循环或一个临时的 table,但那些要求我创建总是 returns 的东西“错误代码:1142。创建命令被用户拒绝.. ..”或“错误代码:1044。用户访问被拒绝......”。
感谢任何帮助或反馈。
您可以列出您想要的日期并汇总:
select m.eom, sum(s.sales)
from (select '2020-01-31' as eom union all
select '2020-02-29' union all
. . .
) m left join
sales s
on s.date < m.eom
group by m.eom;
请注意,您还可以使用递归 CTE 或日历生成日期 table。
对于这个特定的查询,您还可以使用累计和:
select last_day(date) as eom, sum(sales),
sum(sum(sales)) over (order by last_day(date))
from sales
group by eom;
这适用于您的特定示例,但可能不适用于其他逻辑。