Sql COALESCE entire rows?

前端 未结 4 1948
南笙
南笙 2021-01-18 08:21

I just learned about COALESCE and I\'m wondering if it\'s possible to COALESCE an entire row of data between two tables? If not, what\'s the best approach to the following r

4条回答
  •  没有蜡笔的小新
    2021-01-18 08:48

    This should be pretty performant. It uses a CTE to basically build a small table of Customers that have no matching Employee records, and then it simply UNIONs that result with the Employee records

    ;WITH FilteredCustomers (Id, Name, Email, Etc)
    AS
    (
        SELECT  Id, Name, Email, Etc
        FROM    tbl_Customers C
                INNER JOIN tbl_PeopleInCompany PIC
                ON C.Id = PIC.Id
                LEFT JOIN tbl_Employees E
                ON C.Id = E.Id
        WHERE   E.Id IS NULL
    )
    
    SELECT  Id, Name, Email, Etc
    FROM    tbl_Employees E
            INNER JOIN tbl_PeopleInCompany PIC
            ON C.Id = PIC.Id
    
    UNION
    
    SELECT  Id, Name, Email, Etc
    FROM    FilteredCustomers
    

    Using the IN Operator can be rather taxing on large queries as it might have to evaluate the subquery for each record being processed.

提交回复
热议问题