在Where子句SQL Server

时间:2018-11-14 21:36:27

标签: sql sql-server

我只想返回第一个条件不存在的行 然后从同一表返回新条件,以及其他条件: 基本上...:

SELECT *   
FROM Table1     
WHERE

Condition#1: Column1=Column2

Condition#2: AND IF Column1 = Column2 doesn't exist (matching values for same ID) 
             THEN return results where Column3 = Column4

enter image description here

谢谢。

5 个答案:

答案 0 :(得分:0)

我怀疑这可以满足OP的需求,但是逻辑似乎很奇怪...

SELECT {Columns}
FROM YourTable YT
WHERE YT.Column1 = YT.Column2
   OR (YT.Column3 = YT.Column4
  AND  NOT EXISTS(SELECT 1
                  FROM YourTable e
                  WHERE YT.id = e.id
                    AND e.Column1 = e.Column2));

不过,不确定此处的性能如何,因为您可能最终使用该NOT EXISTS进行了表扫描。

答案 1 :(得分:0)

根据评论,这是一种方法。

SELECT *    
FROM Table1      
WHERE Column1 = Column2 
UNION 
SELECT * 
FROM Table2 
WHERE  Column1 != Column2 and Column3 = Column4

答案 2 :(得分:0)

您可以使用简单的布尔值来做到这一点:

WHERE
Column1 = Column2
OR
Column3 = Column4

维恩图:

enter image description here

将返回所有阴影区域,包括当Column1 = Column2和Column3 = Column4(深色阴影交叉点)时

如果您不希望同时满足这两个条件的行,则可以修改逻辑:

WHERE
Column1 = Column2
OR
(Column1 <> Column2 
AND
Column3 = Column4)

除了交叉点为白色且不包括交点之外,维恩看起来都一样。

答案 3 :(得分:0)

首先,您需要检查您的情况。因此,您可以计算表中有多少C1 = C2

SELECT [id], COUNT(CASE WHEN C1 = C2 THEN 1 END) as c1_c2
FROM Table1
GROUP BY [id]

那你有两个条件

首先,当您有c1 = c2时

  (c1 = c2 and c1_c2 > 0 )

当没有c1 = c2时是第二个

  (c1_c2 = 0 and c3 = c4)

SQL DEMO: :因为是OR,而c1_c2的计数决定了该位置的哪一侧工作。

WITH c12 as (
    SELECT [id], COUNT(CASE WHEN C1 = C2 THEN 1 END) as c1_c2_cnt
    FROM Table1
    GROUP BY [id]
) 
SELECT *
FROM Table1 T
JOIN c12 C
  ON T.[id] = C.[id]  
WHERE  ( C.c1_c2_cnt > 0 and T.c1 = T.c2 )
   OR  ( C.c1_c2_cnt = 0 and T.c3 = T.c4 )

输出

enter image description here

答案 4 :(得分:0)

另一种方法:

DECLARE 
    @t TABLE( ID INT, col1 CHAR(1), col2 CHAR(1), col3 INT, col4 INT)

INSERT INTO @t VALUES 
(1234,'A','B',100,100),
(1234,'A','A',100,100),
(2468,'A','C',125,125),
(2468,'A','B',100,150)

SELECT 
    ID
,   col1
,   col2
,   col3
,   col4
FROM (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY ID, col1 ORDER BY col2) RN
    FROM (
        SELECT *
        FROM @t
        WHERE 
            col3 = col4
        AND col1 = col2
        UNION ALL 
        SELECT *
        FROM @t
        WHERE 
            col3 = col4
        AND ID NOT IN(
            SELECT ID
            FROM @t
            WHERE 
                col3 = col4
            AND col1 = col2
            )
    ) D
) E
WHERE 
    RN = 1