Is possible have different conditions for each row in a query?

前端 未结 4 678
甜味超标
甜味超标 2021-01-25 19:26

How I can select a set of rows where each row match a different condition?

Example:

Supposing I have a table with a column called name, I want the

4条回答
  •  温柔的废话
    2021-01-25 20:02

    Assuming that You know how to provide a row number to your rows (ROW_NUMBER() in SQL Server, for instance), You can create a lookup (match) table and join on it. See below for explanation:

    LookupTable:

    RowNum    Value
    1         A
    2         B
    3         C
    

    Your SourceTable source table (assuming You already added RowNum to it-in case You didn't, just introduce subquery for it (or CTE for SQL Server 2005 or newer):

    RowNum Name
    -----------
    1      A
    2      B
    3      C
    4      D
    

    Now You need to inner join LookupTable with your SourceTable on LookupTable.RowNum = SourceTable.RowNum AND LookupTable.Name = SourceTable.Name. Then do a left join of this result with LookupTable on RowNum only. If there is LookupTable.RowNum IS NULL in final result then You know that there is no complete match on at least one row.

    Here is code for joins:

    SELECT T.*, LT2.RowNum AS Matched 
    FROM LookupTable LT2
    LEFT JOIN 
    (
        SELECT ST.*
        FROM SourceTable ST
        INNER JOIN LookupTable LT ON LT.RowNum = ST.RowNum AND LT.Name = ST.Name
    ) T
        ON LT2.RowNum = T.RowNum
    

    Result set of above query will contain rows with Matched IS NULL if row is not matching condition from LookupTable table.

提交回复
热议问题