简化重复SELECT ... IN查询

时间:2015-10-27 05:21:58

标签: sql sqlite select

我查询了表单

SELECT a, b, c from Tbl where [conditions] IN
    (SELECT a from Tbl where [conditions]
        GROUP BY a HAVING COUNT(*) > N)
    ORDER BY a DESC, b LIMIT 100

[conditions]基本上是一系列AND语句,a是一个可能重复的列。列a + b是一个独特的组合。目前我只是使用GROUP BY子句来使COUNT(*) > N起作用。我想为满足[conditions]且至少有N行的列条目返回行。正如您所看到的,查询与重复条件基本相同。有什么更好的方法来实现上述目标?

感谢。

1 个答案:

答案 0 :(得分:-1)

SELECT a, b, c FROM Tbl
WHERE a IN
(SELECT a FROM Tbl
HAVING COUNT(*) > N AND CASE [conditions] THEN 1 ELSE 0 END = 1
GROUP BY a, CASE [conditions] THEN 1 ELSE 0 END); 

我猜不是最好的选择吗?

SELECT a, b, c FROM Tbl
WHERE a IN (
SELECT a FROM
( SELECT a,
CASE WHEN [conditions] THEN 1 ELSE 0 END AS con FROM Tbl ) T
WHERE con = 0 
HAVING COUNT(*) > N
GROUP BY a, con);