2

当 7 个可用列中的任何 3 个包含该行的数据时,我需要包含行。有没有做类似事情的最佳实践?我想出的解决方案似乎很好,只是想知道是否有更可接受的模式?有关详细信息,请参见此处。以下是我要完成的工作的要点。

CREATE TABLE Customer(
    FirstName varchar(50) NULL,
    LastName varchar(50) NULL,
    AddressLine1 varchar(100) NULL,
    AddressLine2 varchar(100) NULL,
    City varchar(50) NULL,
    State char(3) NULL,
    Country char(2) NULL)

Insert Into Customer Values('Bob', null, '', 'addr2', 'city', '', null)
Insert Into Customer Values('', '', '', '', '', '', '')
Insert Into Customer Values(null, null, null, null, null, null, null)

SELECT *
    FROM Customer
    WHERE (CASE WHEN IsNull(FirstName, '') = '' THEN 0 ELSE 1 END
           + CASE WHEN IsNull(LastName, '') = '' THEN 0 ELSE 1 END
           + CASE WHEN IsNull(AddressLine1, '') = '' THEN 0 ELSE 1 END
           + CASE WHEN IsNull(AddressLine2, '') = '' THEN 0 ELSE 1 END
           + CASE WHEN IsNull(City, '') = '' THEN 0 ELSE 1 END
           + CASE WHEN IsNull(State, '') = '' THEN 0 ELSE 1 END
           + CASE WHEN IsNull(Country, '') = '' THEN 0 ELSE 1 END) 
            >= 3
4

1 回答 1

4

替代。

SELECT *
FROM   Customer
WHERE  3 <= ((SELECT Count(NULLIF(C, ''))
              FROM   (VALUES (FirstName),
                             (LastName),
                             (AddressLine1),
                             (AddressLine2),
                             (City),
                             (State),
                             (Country)) V(C))) 
于 2012-06-08T21:45:33.720 回答