mysql - 如何对另一列的 DISTINCT 值和 GROUP BY 日期求和?

标签 mysql sql

我们如何才能仅在同一日期对每个事件求和金额并为每个日期输出一行?该查询不起作用。

SELECT SUM(amount), type, date FROM table GROUP BY DISTINCT date;

表格

+----+------------+-----------+---------+
| id |    date    | activity  | amount  |
+----+------------+-----------+---------+
| 1  | 2017-12-21 | Shopping  | 200     |
| 2  | 2017-12-21 | Gift      | 240     |
| 3  | 2017-12-23 | Give Away | 40      |
| 4  | 2017-12-24 | Shopping  | 150     |
| 5  | 2017-12-25 | Give Away | 120     |
| 6  | 2017-12-25 | Shopping  | 50      |
| 7  | 2017-12-25 | Shopping  | 500     |
+----+------------+-----------+---------+

所需结果

+------------+-----------+------+-----------+
|    date    | Shopping  | Gift | Give Away |
+------------+-----------+------+-----------+
| 2017-12-21 | 200       | 240  |           |
| 2017-12-23 |           |      | 40        |
| 2017-12-24 | 150       |      |           |
| 2017-12-25 | 550       |      | 120       |
+------------+-----------+------+-----------+

最佳答案

用途:

select `date`, 
  sum(if (activity='Shopping', amount, null)) as 'Shopping',
  sum(if (activity='Gift', amount, null)) as 'Gift',
  sum(if (activity='Give Away', amount, null)) as 'Give Away'
from table
group by `date`

关于mysql - 如何对另一列的 DISTINCT 值和 GROUP BY 日期求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48474691/

相关文章:

php - 使用php问题的mysql更新表单不断更新旧信息而不是新更新

mysql - 让mysql查询更快

java - PHP 比较从 java 接收到的值

python - 在 Python 中连接两个 SQL 字符串列表

mysql - SQL-DBDL 如何约束父类(super class)参与子类?

mysql转储: Got error: 1017: Can't find file: './access.frm' (errno: 13) when using LOCK TABLES

python - mysql-python的pip安装抛出clang错误

mysql - 从一个表连接到另一个表中选择最近的结果

mysql - 一对多关系的 SQL 查询

mysql - 根据第二个表的另一个值在第一个表中选择一个值(sql)