按外键和日期分组数据,按日期汇总
Posted
技术标签:
【中文标题】按外键和日期分组数据,按日期汇总【英文标题】:Group data by foreign key and date with total by date 【发布时间】:2021-03-09 07:15:45 【问题描述】:我需要帮助来选择按组织和日期进行的每日付款和分组。 按日期分组,然后是付款总数和每天的付款总额 表格如下,
organizations
-----------------------------
| id | name |
+-------------+-------------+
| 1 | org_1 |
+-------------+-------------+
| 2 | org_2 |
+-------------+-------------+
| 3 | org_2 |
-----------------------------
payments
------------------------------------------------------------
| id | org_id | amount | date_created |
+-----------+------------+-------------+-------------------+
| 1 | 2 | 20 | 2020-11-06 |
+-----------+------------+-------------+-------------------+
| 2 | 2 | 10 | 2020-11-06 |
+-----------+------------+-------------+-------------------+
| 3 | 1 | 50 | 2020-11-05 |
+-----------+------------+-------------+-------------------+
| 4 | 2 | 10 | 2020-11-05 |
------------------------------------------------------------
预期结果
----------------------------------------------------------------------------------------------
| date_created | total_amount | num_payments | org_1 | org_2 | org_3 |
+----------------+----------------+-------------------+-----------+-------------+------------+
| 2020-11-06 | 30.00 | 2 | 0 | 2 | 0 |
+----------------+----------------+-------------------+-----------+-------------+------------+
| 2020-11-05 | 60.00 | 2 | 1 | 1 | 0 |
+----------------+----------------+-------------------+-----------+-------------+------------+
【问题讨论】:
【参考方案1】:使用条件聚合:
select p.date_created,
sum(p.amount) as total_amount,
count(*) as num_payments,
sum(case when o.name = 'org_1' then p.amount else 0 end) as org_1,
sum(case when o.name = 'org_2' then p.amount else 0 end) as org_2,
sum(case when o.name = 'org_3' then p.amount else 0 end) as org_3
from payments p
inner join organizations o on o.id = p.org_id
group by p.date_created
【讨论】:
谢谢,但您的查询将组织的数量限制为只有这 3 个如果添加新组织会发生什么情况 @Wells:那么您需要在select
子句中添加更多条件表达式。否则,您需要动态 SQL,这要复杂得多。以上是关于按外键和日期分组数据,按日期汇总的主要内容,如果未能解决你的问题,请参考以下文章