2017-08-29 75 views
1

我有如下表:集团通过多对多表

performance 
    --id 
    --color 
    --installs 
    --date 

performance_groups 
    --id 
    --performance_id 
    --group_id 

我想有一个SQL是这样的:

SELECT color, targeting_id, SUM(installs) as installs 
FROM performance, performance_groups 
GROUP BY color, group_id 

但是我想对于做分组所有的团体。

例如:

performance 
id  color  installs date 
1  Blue  5   2017-07-05 
2  Red  10   2017-07-04 
3  Blue  10   2017-07-04 
4  Blue  10   2017-07-05 

performance_groups 
id performance_id group_id 
1 1    1 
2 1    2 
3 2    3 
4 3    1 
5 3    2 
6 4    1 
7 4    3 

我想获得这样的结果:

color group_ids installs 
Blue 1,2  15 
Red 3  10 
Blue 1,3  10 

回答

0

感谢戈登和镭我得到了一个灵感,我的答案。

最终的解决方案是:

with pg as(
    select performance_id, array_agg(distinct group_id) as groups from performance_groups 
    group by performance_id 
) 
select groups, sum(installs) from performance join pg 
on pg.performance_id = performance.id 
group by groups 

见工作sqlfiddle

2

决不FROM子句中使用逗号。始终使用正确的,明确的JOIN语法。然后

您的查询似乎是一个JOINGROUP BY

select p.color, string_agg(pg.group_id) as groups, 
     sum(installs) as installs 
from performance p join 
    performance_groups pg 
    on pg.performance_id = p.id 
group by color; 
+0

感谢。我正在检查它 - 你能否详细说明连接和逗号之间的区别? – Dejell

+0

'JOIN'是正确的语法。逗号是古老的语法,已超过二十年。 –

1

使用array_agg,不要忘了明显。连接可能会产生重复。

select p.color, array_agg(distinct pg.group_id) as groups, 
     sum(distinct installs) as installs 
from performance p 
join performance_groups pg 
    on pg.performance_id = p.id 
group by color; 

sqlfiddle demo

+0

听起来像是正确的答案。将检查更多和upate – Dejell

0
We are using STUFF,XML PATH and GROUP BY in SQL 2008. 

代码:

select f.color, 
    (SELECT STUFF((SELECT ',' + convert(varchar(5),j.group_id) 
    FROM (select distinct g.group_id from performance_groups g 
    where g.performance_id in (select id from performance where color= 
    f.color)) j FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, 
    '')) as group_ids, 
    SUM(f.installs) installs 
    from performance f group by color 

OUTPUT:

color group_ids installs 
Blue 1,2   15 
Red  3   10 
+0

但我使用postgres sql - 它有什么帮助? – Dejell