【问题标题】:SQL - Combined Group BySQL - 组合分组依据
【发布时间】:2020-04-10 16:51:52
【问题描述】:

试图弄清楚如何组合这两个查询,但正在努力解决。

1.

select ia.name, count(archived_i) from (
    select * from incident i
    where i.archived = true
) as archived_i
right join incident_action ia on archived_i.incident_action_id = ia.id
group by ia.name
order by ia.name;

产量

Detention   3
Expulsion   0
Warning     2

2.

select in_s.name, count(archived_i) from (
    select * from incident i
    where i.archived = true
) as archived_i
right join incident_severity as in_s on archived_i.incident_severity_id = in_s.id
group by in_s.name
order by in_s.name;

产量

High    0
Low     5

我想把这些结合起来形成一些东西

Detention   High   0
Detention   Low    3
Expulsion   High   0
Expulsion   Low    0
Warning     High   0
Warning     Low    2

什么是正确、高效的方法?

【问题讨论】:

  • 一个CROSS JOIN?
  • @TheImpaler 具体是什么方式?我尝试交叉加入,但得到重复计数。我想将计数分布在所有 6 种组合中。

标签: sql postgresql join group-by left-join


【解决方案1】:

你可以cross join引用表severity和action来生成所有可能的组合,然后把事件表带上left join。最后一步是聚合。

select ina.name action, ins.name severity, count(i.archived_i)
from incident_severity ins
cross join incident_action ina
left join incident i 
    on  i.incident_action_id = ina.id
    and i.incident_severity_id = ins.id
    and i.archived
group by ina.name, ins.name

【讨论】:

  • 我应该在 i.archived 上建立索引,还是在多个列上建立索引?
  • @jkossis:为了获得此查询的性能,您需要在incident(incident_action_id, incident_severity_id, archived) 上建立一个多列索引。
【解决方案2】:

在不更改查询的情况下,您可以进行交叉连接。例如:

select
  x.name,
  y.name,
  'x'
from (
  select ia.name, count(archived_i) from (
    select * from incident i
    where i.archived = true
  ) as archived_i
  right join incident_action ia on archived_i.incident_action_id = ia.id
  group by ia.name
  order by ia.name
) x
cross join (
  select in_s.name, count(archived_i) from (
    select * from incident i
    where i.archived = true
  ) as archived_i
  right join incident_severity as in_s 
    on archived_i.incident_severity_id = in_s.id
  group by in_s.name
  order by in_s.name
) y

【讨论】:

  • 我并不真正想要 'x' 字符。我正在寻找加起来为 5 的计数以分布在这些组合中。
  • @TheImapler 对不起,我试图传达这些数字是未知的,以及我想要检索的那些。更新了问题。
猜你喜欢
  • 1970-01-01
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多