我的SQL-COUNT字段在多表上按其他字段分组

时间:2018-12-10 17:07:49

标签: sql sum multi-table

我错过了创建正确的请求的机会。

我的要求是:

select actionreal, sum(nb_actions) nb_actions from ( 
  select actionreal, count(distinct departement) nb_actions 
  from militant_action_nutrition 
  where actionreal in (1, 2, 3) 
  group by actionreal 
  union 
  select actionreal, count(distinct departement) nb_actions 
  from militant_action_jna 
  where actionreal in (1, 2, 3) 
  group by actionreal 
) t
group by actionreal

我需要通过actionreal在2个表上获得不同部门的数量。

在militant_action_nutrition中,我有
对于actionreal = 1,“ Bas-Rhin”和“ Manche”,对于actionreal = 2,“ Bas-Rhin”和“ Manche”。

在militant_action_jna我有
对于actionreal = 1,“ Bas-Rhin”,“ Manche”和“ Yonne”,对于actionreal = 2,“ Bas-Rhin”和“ Manche”。

我的请求结果是:

1 | 5
2 | 2

但是我需要结果:

1 | 3
2 | 2

谢谢您的帮助。

1 个答案:

答案 0 :(得分:0)

首先进行合并,然后分组依据:

select actionreal, count(distinct departement) nb_actions from ( 
    select actionreal, departement
    from militant_action_nutrition 
    where actionreal in (1, 2, 3) 
    union 
    select actionreal, departement 
    from militant_action_jna 
    where actionreal in (1, 2, 3)
) t
group by actionreal

在我知道的所有数据库中,UNION操作员实际上会删除重复的条目,因此最终计数应该是您想要的。