SQL SELECT ID WHERE具有相同ID的行具有不同的值

问题描述 投票:0回答:1

我需要一些帮助来创建跨行的SQL语句。

SELECT SZ.Stammindex AS ID, sEbene1, sEbene2, sEbene3
FROM SuchbaumZuordnung SZ 
LEFT JOIN Suchbaum S SZ.gSuchbaumID = S.gID
WHERE (sEbene1 IN ('Test1') 
       AND (sEbene2 IN ('Test2') OR sEbene2 IS NULL) 
       AND sEbene3 IS NULL)

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS94ZVlmZC5wbmcifQ==” alt =“这是我到目前为止得到的东西”>

正如您在屏幕快照中所看到的,我选择了ID = 10004和ID = 10005。但是实际上我只希望显示ID = 10005。如前所述,我正在尝试对行进行过滤。

我的目标是获取所有ID,其中所有条件都与“ AND”相关联,如下所示:

WHERE (sEbene1 IN ('Test1') 
       AND (sEbene2 IN ('Test2') *AND* sEbene2 IS NULL) 
       AND sEbene3 IS NULL)

但是不会返回任何内容。

希望你们能帮助我。

sql sql-server ssms
1个回答
0
投票
我怀疑您想要:

SELECT SZ.Stammindex AS ID FROM SuchbaumZuordnung SZ WHERE EXISTS (SELECT 1 FROM Suchbaum S WHERE SZ.gSuchbaumID = S.gID AND S.sEbene1 IN ('Test1') AND sEbene2 IN ('Test2') ) AND EXISTS (SELECT 1 FROM Suchbaum S WHERE SZ.gSuchbaumID = S.gID AND S.sEbene2 IS NULL AND S.sEbene3 IS NULL );

这正在Suchbaum中寻找两个

different行,每个行都与条件之一匹配。


0
投票
考虑到您只有3列要检查不同的行,似乎可以通过CTE和Windowed COUNT轻松实现:

WITH CTE AS( SELECT SZ.Stammindex AS ID, S.sEbene1, --Guessed the table alias S.sEbene2, --Guessed the table alias S.sEbene3, --Guessed the table alias COUNT(DISTINCT CONCAT(ISNULL(S.S.sEbene1,'-'),ISNULL(S.sEbene2,'-'),ISNULL(S.sEbene3,'-'))) OVER (PARTITION BY SZ.Stammindex) AS DistinctRows FROM SuchbaumZuordnung SZ LEFT JOIN Suchbaum S ON SZ.gSuchbaumID = S.gID) --This was missing the ON in your sample SELECT C.Stammindex, C.sEbene1, C.sEbene2, C.sEbene3 FROM CTE C WHERE C.DistinctRows > 1;

如果纯粹是一个ID多于1行(可能是相同的,那么您可以只使用COUNT

WITH CTE AS( SELECT SZ.Stammindex AS ID, S.sEbene1, --Guessed the table alias S.sEbene2, --Guessed the table alias S.sEbene3, --Guessed the table alias COUNT(*) OVER (PARTITION BY SZ.Stammindex) AS [Rows] FROM SuchbaumZuordnung SZ LEFT JOIN Suchbaum S ON SZ.gSuchbaumID = S.gID) SELECT C.Stammindex, C.sEbene1, C.sEbene2, C.sEbene3 FROM CTE C WHERE C.[Rows] > 1;

© www.soinside.com 2019 - 2024. All rights reserved.