【发布时间】:2019-10-05 12:36:11
【问题描述】:
我不明白为什么我的查询没有按我指定的列对计数结果进行分组。相反,它会计算“un”子表中所有出现的结果 ID。
我错过了什么?
我的示例数据库的完整结构和我尝试过的查询在这里:
https://www.db-fiddle.com/f/4HuLpTFWaE2yBSQSzf3dX4/4
CREATE TABLE combination (
combination_id integer,
ticket_id integer,
outcomes integer[]
);
CREATE TABLE outcome (
outcome_id integer,
ticket_id integer,
val double precision
);
insert into combination
values
(510,188,'{52,70,10}'),
(511,188,'{52,56,70,18,10}'),
(512,188,'{55,70,18,10}'),
(513,188,'{54,71,18,10}'),
(514,189,'{52,54,71,18,10}'),
(515,189,'{55,71,18,10,54,56}')
;
insert into outcome
values
(52,188,1.3),
(70,188,2.1),
(18,188,2.6),
(56,188,2),
(55,188,1.1),
(54,188,2.2),
(71,188,3),
(10,188,0.5),
(54,189,2.2),
(71,189,3),
(18,189,2.6),
(55,189,2)
with un AS (
SELECT combination_id, unnest(outcomes) outcome
FROM combination c JOIN
outcome o
on o.ticket_id = c.ticket_id
GROUP BY 1,2
)
SELECT combination_id, cnt
FROM (SELECT un.combination_id,
COUNT(CASE WHEN o.val >= 1.3 THEN 1 END) as cnt
FROM un JOIN
outcome o
on o.outcome_id = un.outcome
GROUP BY 1
) x
GROUP BY 1, 2
ORDER BY 1
预期结果应该是:
510 2
511 4
512 2
513 3
514 4
515 4
【问题讨论】:
-
表定义应该在您的问题中,而不仅仅是在需要从多个来源执行脚本的小提琴中。
-
好的,更新后
-
您能用简单的英语解释一下您要计算的确切内容吗? “预期结果”中的
514 4似乎没有加起来。应该是514 3,对吧?最佳查询取决于实际表定义,还显示约束(最重要的是PK、FK、UNIQUE)和有关数据分布的信息... -
现在我意识到我错过了组合 514 和 515 的结果表中的一些条目,这就是存在差异的原因。明天我会更新我的帖子并检查您的答案,因为手机不舒服。提前致谢。
标签: sql postgresql count case postgresql-9.4