2017-04-14 49 views
0

当我运行一个查询,这些都对我的结果:的Postgres组由

id account_id score active item_id 
5 78   9  true 4 
6 78   1  true 4 
7 78   9  true 6 
8 78   5  true 7 
9 78   5  true 8 
10 78   5  true 8 

我想输出看起来像这样通过合并ITEM_ID基于配乐的:

id account_id score active item_id 
* 78   10  true 4 
7 78   9  true 6 
8 78   5  true 7 
* 78   10  true 8 

我的查询返回的信息是这样的:

SELECT item.id, item.account_id, itemaudit.score, itemrevision.active, itemaudit.item_id 
from item 
left join itemrevision on item.id = itemrevision.id 
join itemaudit on item.id = itemaudit.id 
where itemrevision.active = true 
; 

我失去了该位时,“ITEM_ID”不显着,合并/总和'分数'的值。我不知道如何做这一步。

的模式是这样的:

CREATE TABLE item 
(id integer, account_id integer); 

CREATE TABLE itemaudit 
(id integer, item_id integer, score integer); 

CREATE TABLE itemrevision 
(id int, active boolean, item_id int); 


INSERT INTO item 
    (id, account_id) 
VALUES 
    (5, 78), 
    (6, 78), 
    (7, 78), 
    (8, 78), 
    (9, 78), 
    (10, 78)  
; 


INSERT INTO itemaudit 
    (id, item_id, score) 
VALUES 
    (5, 4, 5), 
    (6, 4, 1), 
    (7, 6, 9), 
    (8, 7, 10), 
    (9, 8, 1), 
    (10, 8, 9) 
; 

INSERT INTO itemrevision 
    (id, active, item_id) 
VALUES 
    (5, true, 4), 
    (6, true, 4), 
    (7, true, 6), 
    (8, true, 7), 
    (9, true, 7), 
    (10, true, 8) 
; 
+0

你想要什么该查询的输出是什么? –

+0

你为什么还原我的编辑?我添加了'CREATE TABLE AS'你... –

+0

我恢复的编辑,因为它给人的印象是数据是在现有的表,而事实上其在几个不同的禁止进入查询结果。我想避免这种困惑。 – Publiccert

回答

1

如果我理解正确的话,你只需要一个聚集查询:

select ia.item_id, sum(ia.score) as score 
from item i join -- the `where` clause turns this into an inner join 
    itemrevision ir 
    on i.id = ir.id join 
    itemaudit ia 
    on i.id = ia.id 
where ir.active = true 
group by ia.item_id; 

注:

  • 我改变了left joininner join,因为where条款有这样的效果呢。
  • 表别名使查询更易于编写和阅读。
  • 在聚合查询,其他列是不恰当的。
+0

解决了最初的问题,谢谢!有没有办法保留我在示例中展示的结构,但将“item_id”行结合并将它们的分数添加到该行中? – Publiccert

+0

我已经添加了所需输出的示例。 – Publiccert

1

我想你想是这样的..

SELECT 
    CASE 
    WHEN array_length(array_agg(id),1) = 1 
     THEN (array_agg(id))[1]::text 
    ELSE '*' 
    END AS id, 
    account_id, 
    sum(score) AS score, 
    item_id 
FROM item 
GROUP BY account_id, item_id 
ORDER BY account_id, item_id; 

id | account_id | score | item_id 
----+------------+-------+--------- 
* |   78 | 10 |  4 
7 |   78 |  9 |  6 
8 |   78 |  5 |  7 
* |   78 | 10 |  8 
(4 rows) 

虽然这是你想要的简单版本更详细和更好的。

SELECT 
    array_agg(id) AS id, 
    account_id, 
    sum(score) AS score, 
    item_id 
FROM item 
GROUP BY account_id, item_id 
ORDER BY account_id, item_id; 

    id | account_id | score | item_id 
--------+------------+-------+--------- 
{5,6} |   78 | 10 |  4 
{7} |   78 |  9 |  6 
{8} |   78 |  5 |  7 
{9,10} |   78 | 10 |  8 
(4 rows)