我有一个返回类似于下面结果集的查询:
Quarter | Count
------- | -----
1 Q2 2009 | NULL
2 Q2 2009 | NULL
3 Q2 2009 | NULL
4 Q3 2009 | 26
5 Q3 2009 | 27
6 Q3 2009 | NULL
我不希望第1-3行,因为它们的组合Quarter-Count为NULL。但我确实想要第3-6行,因为同一季度中至少有一个Count不是NULL。
我如何从上面的结果集来到这个:
Quarter | Count
------- | -----
1 Q3 2009 | 26
2 Q3 2009 | 27
3 Q3 2009 | NULL
感谢。
答案 0 :(得分:2)
SELECT *
FROM mytable mo
WHERE EXISTS
(
SELECT NULL
FROM mytable mi
WHERE mi.quarter = mo.quarter
AND mi.count IS NOT NULL
)
答案 1 :(得分:2)
SELECT
Quarter, Count
FROM
MyTable M
WHERE
EXISTS (SELECT *
FROM MyTable m2
WHERE m2.Count IS NOT NULL AND m.Quarter = m2.Quarter)
答案 2 :(得分:1)
您可以利用聚合函数忽略null的事实,并执行以下操作:
SELECT * FROM myTable m1 inner join
(
SELECT quarter as q2 from myTable
GROUP BY quarter
HAVING sum(count) is not null
) as m2 on m1.quarter = m2.q2
哪个执行计划可能比EXISTS更好 - 可能没有。