用于提取多个列条件的T-SQL查询

时间:2012-05-30 15:18:01

标签: sql-server

当且仅当它们对sql server中的所有后续列都有一个值'Y'时,我需要选择所有行。

Bike_Racks_Lockers  SHELTERS    Telephone   Lighting    FENCES

        N              N            Y           Y          Y                    
        N              N            N           N          Y                
        N              N            N           N          N                
        Y              Y            Y           Y          Y                
        ?              ?            ?           ?          ?                 
        N              N            N           N          N

3 个答案:

答案 0 :(得分:2)

select * from yourtable where Bike_Racks_Lockers = 'Y' and  SHELTERS = 'Y' and 
Telephone = 'Y' and Lighting = 'Y' and FENCES = 'Y'

修改

在这种情况下,请单独进行检查并插入其他表格。例如:

insert into othertable selct * from yourtable where Bike_Racks_Lockers = 'Y' 

insert into someothertable selct * from yourtable where SHELTER = 'Y' 

答案 1 :(得分:2)

ColumnName='Y'子句中的每一列使用WHERE

SELECT Bike_Racks_Lockers, SHELTERS, Telephone, Lighting, FENCES
FROM [TableName]
WHERE Bike_Racks_Lockers='Y'
AND SHELTERS='Y'
AND Telephone='Y'
AND Lighting='Y'
AND FENCES='Y'

但是,老实说,我不确定这个结果集的重点是什么?

答案 2 :(得分:2)

SELECT * 
FROM   mytable 
WHERE  Bike_Racks_Lockers = SHELTERS 
       AND Telephone  = Bike_Racks_Lockers
       AND Lighting = Bike_Racks_Lockers 
       AND FENCES = Bike_Racks_Lockers 
       AND Bike_Racks_Lockers = 'Y'