如果问题很愚蠢,谢谢您的时间和歉意。我有一个联合查询的结果,如下所示。如您所见,A和C都具有value2而不是NULL。我如何只能选择B?我会提供我的sql尝试,但我用尽了所有想法。我尝试了count()和sum()等方法,但是我总是选择A B C,而我只想获得B。 谢谢。
value1 value2
A NULL
A 1
B NULL
C 2
C 3
C NULL
非常感谢您的帮助。我得到了答案以及更多!你们都很棒!
答案 0 :(得分:1)
这是您想要的吗?
select value1
from t
group by value1
having count(value2) = 0;
答案 1 :(得分:0)
我不确定您是卡在UNION
还是GROUP BY
上,所以这是我的示例:
SELECT VALUE1 FROM
(
--put your UNION query in here, I'm just building your example data
SELECT 'A' AS VALUE1, NULL AS VALUE2
UNION
SELECT 'A' AS VALUE1, 1 AS VALUE2
UNION
SELECT 'B' AS VALUE1, NULL AS VALUE2
UNION
SELECT 'C' AS VALUE1, 2 AS VALUE2
UNION
SELECT 'C' AS VALUE1, 3 AS VALUE2
UNION
SELECT 'C' AS VALUE1, NULL AS VALUE2
) AS THETABLE
GROUP BY VALUE1
HAVING COUNT(VALUE2) = 0
结果:
有很多方法可以做到这一点,这只是其中一种。
答案 2 :(得分:0)
您是否熟悉子查询或CTE?它们使您可以将结果集像表一样对待。
所以...
WITH CTE
( SELECT * -- Put your union query hear
FROM YourUnionQuery
)
-- Then this is the actual transformation you're looking for
SELECT C1.*
FROM CTE C1
WHERE NOT EXISTS
( SELECT 1
FROM CTE C2
WHERE C2.value2 IS NOT NULL
AND C2.value1 = C2.value1
)