gpt4 book ai didi

Mysql 添加新列以供选择

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

我有下表

+-----+------------------+-------------+
| id | name |month_1 |
+-----+------------------+-------------+
| 1 | anna | 15 |
| 2 | bin | 20 |
+-----+------------------+-------------+

当我做出选择时,我想再添加一列。

例如

SELECT id,name, money as month_1 FROM test where month(day)='1';

我想添加一列,如下所示:

SELECT id,name, money as month_1,money as month_2 
FROM test
where where month(day)='1',where month(day)='2'

+-----+------------------+-------------+------------+
| id | name | month_1 |month_2 |
+-----+------------------+-------------+------------+
| 1 |anna | 15 | 10 |
| 2 | bin | 20 | 0 |
+-----+------------------+-------------+------------+

最佳答案

您可以使用条件聚合:

SELECT id,name,
SUM(CASE WHEN month(day) = 1 THEN money ELSE 0 END) as month_1,
SUM(CASE WHEN month(day) = 2 THEN money ELSE 0 END) as month_2
FROM test
GROUP BY id, name;

您可能想也可能不想在聚合中包含月份和年份。

关于Mysql 添加新列以供选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46249459/

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