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

时间:2020-01-30 12:39:37

标签: sql sql-server ssms

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

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

This is what I got so far

如您在屏幕截图中所见,我选择了ID = 10004和ID = 10005。但是实际上我只希望显示ID = 10005。如上所述,我正在尝试跨行过滤。

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

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

但这不会返回任何内容。

编辑

Table Suchbaum structure

Table SuchbaumZuorndung structure

我希望你们能帮助我。

2 个答案:

答案 0 :(得分: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中查找两行不同行,每行匹配条件之一。

答案 1 :(得分: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;