【问题标题】:How to join grouped and filtered fields on table?如何在表格中加入分组和过滤字段?
【发布时间】:2021-06-19 08:33:21
【问题描述】:

我有这个数据集,我想按 user_id 分组并按类别对值求和

id user_id category value
0 1 1 10
1 1 1 20
2 1 2 10
3 1 2 30
4 1 3 10
5 2 3 40

我想要一个选择返回一个表,其中包含一个 user_id 元素,每个类别值一个字段(这些是已知的,只能是 1、2 或 3)

user_id category_1 category_2 category_3
1 30 40 10
2 0 0 40

我找到的唯一解决方案是:

select
  r.user_id as user_id,
  rt_c1.value as category_1_value,
  rt_c2.emissions_change_co2e as scope2_co2e_emissions,
  rt_c3.emissions_change_co2e as scope3_co2e_emissions
from tablename as r
join (select 
  rt.user_id
  rt.category as category,
  sum(rt.value) as value
from tablename as rt
group by rt.user_id, rt.category) as rt_c1
on rt_c1.user_id = r.user_id and rt_c1.category = 1
join (select 
  rt.user_id
  rt.category as category,
  sum(rt.value) as value
from tablename as rt
group by rt.user_id, rt.category) as rt_c2
on rt_c2.user_id = r.user_id and rt_c2.category = 2
join (select 
  rt.user_id
  rt.category as category,
  sum(rt.value) as value
from tablename as rt
group by rt.user_id, rt.category) as rt_c3
on rt_c3.user_id = r.user_id and rt_c3.category = 3

【问题讨论】:

  • 在您的子查询中使用Count 函数,然后使用Having 子句或ON 子句检查子查询中的函数,或在Where 子句中最后检查。
  • 对不起@Thiyagu 我不明白你的建议:thinking:
  • 您使用的是 SQL Server 还是 PostgreSQL?
  • 实际上是 PostgresSQL

标签: sql postgresql aggregation


【解决方案1】:

也许是一个简单的条件聚合

示例

Select user_id
      ,sum( case when category=1 then value else 0 end) as category_1
      ,sum( case when category=2 then value else 0 end) as category_2 
      ,sum( case when category=3 then value else 0 end) as category_3
 From  YourTable
 Group By user_id

【讨论】:

  • @BrunoLoops 总是乐于提供帮助
  • @BrunoLoops:或者你可以使用count(*) filter (where category = 1) as category_1
  • @a_horse_with_no_name 除了COUNT(*) != SUM(value)
  • 我看到 SQL Server 标记现在消失了。
  • @MatBailie:对不起,对:sum(value) filter (where ...)
猜你喜欢
  • 2022-01-09
  • 1970-01-01
  • 2017-07-24
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多