当至少其中一个满足条件2时,SQL获取满足条件1的所有行

时间:2018-05-21 13:09:14

标签: sql psql

我的表格A包含UNIQUE (ID, FK)组合和modified列。

我需要将表A的所有条目与FK分组,当其中至少有一个条目与基于CONDITION的{​​{1}}匹配时。

这就是我现在正在做的事情

modified

问题是SELECT * FROM (SELECT COUNT(*) AS count, FK, MAX(modified) FROM A GROUP BY FK) AS A WHERE (modified > date1 AND modifed <= date2) 提供的记录数量非常少,例如来自CONDITION的1%的记录。我不必要地在整个桌子上运行GROUP BY

感谢大家的帮助,这是因为我已经了解到你的努力,虽然看起来多余GROUP BY是这种情况的最佳解决方案。

3 个答案:

答案 0 :(得分:1)

SELECT FK, MAX(modified) m
FROM A 
GROUP BY FK
HAVING (m > date1 AND m <= date2)

这是Postgres模拟

http://sqlfiddle.com/#!17/2230a/6

SELECT FK, MAX(modified) AS m
FROM A 
GROUP BY FK
HAVING (MAX(modified) > (now()-INTERVAL '1 DAY') AND MAX(modified) <= now())

答案 1 :(得分:1)

您可以使用HAVING简化表达式:

SELECT FK, MAX(modified)
FROM A
GROUP BY FK
HAVING SUM(CASE WHEN modified > date 1 and modifed < date2 THEN 1 ELSE 0 END) > 0;

这不会改变性能。为此,请使用EXISTS(或IN):

select fk, max(modified)
from a
where exists (select 1
              from a a2
              where a2.fk = a.fk and a2.modified > date1 and a2.modified < date2
             )
group by fk;

这会在 group by之前过滤,因此它应该使聚合更有效率。您确实需要a(fk, modified)上的索引。

答案 2 :(得分:0)

您不需要在group by之前添加行where

之前使用group by条款
SELECT COUNT(*) AS count, MAX(modified) 
WHERE (modified > date1 OR modifed <= date2)
FROM A 
GROUP BY FK;