我想选择ColA
的所有不同值,ColB
样本表:
ColA ColB
A 1
A 2
B 1
C 2
C 2
D NULL
E 1
E 2
E 2
E 3
期望的结果:所有ColA值至少有一次1和2作为ColB值:
A (has 1 once, has 2 once)
E (has 1 once, has 2 twice)
我知道我必须使用GROUP BY
但不知道确切的聚合函数,我应该使用哪一个?
SELECT ... FROM MyTable
GROUP BY ColA
HAVING at_least_values(ColB, (1, 2)) // something like this
什么是一个好的解决方案?
答案 0 :(得分:3)
您可以使用条件逻辑计算having
子句中的值:
having sum(case when colB = 1 then 1 else 0 end) >= 1 and
sum(case when colB = 2 then 1 else 0 end) >= 1
答案 1 :(得分:2)
intersect
是一种方法。
SELECT ColA FROM MyTable where colB = 1
intersect
SELECT ColA FROM MyTable where colB = 2
答案 2 :(得分:1)
你走在正确的轨道上。您可以使用WHERE子句过滤ColB中的所有1和2。然后使用HAVING子句过滤两个值(DISTINCT COUNT为2)的记录。
-- Return all ColA with a ColB of 1 and 2.emphasized text
SELECT
ColA
FROM
Mytable
WHERE
ColB IN (1, 2) -- Only 1s and 2s required.
GROUP BY
ColA
HAVING
COUNT(DISTINCT ColB) = 2 -- Must have both values.
或者,您可以使用INTERSECT运算符。这允许您查找两个查询中出现的记录。见下面的例子。
SELECT
ColA
FROM
Mytable
WHERE
ColB = 1
GROUP BY
ColA
INTERSECT
SELECT
ColA
FROM
Mytable
WHERE
ColB = 2
GROUP BY
ColA