在Where子句中使用Case语句

时间:2012-07-09 16:59:34

标签: sql sql-server sql-server-2005 case where-clause

在我的查询中,我有以下条件

left Join Table2 on Table2.Id = Table1.Id and Table2.status in  ('Close', 'Open')

由于左连接,上面的条件给了我额外的2行。我注意到如果我在条件中只有关闭或打开它返回正确的行数。

要解决这个问题,我试图写这样的东西

And  Table2.status = (Case Table2.status
                WHEN 'Open' Then 'Open'
                When 'Close' Then 'Close'   
                 End ) 

但是这仍然会返回2个额外的行。关于如何解决这个问题的任何建议??

2 个答案:

答案 0 :(得分:1)

你可以这样做:

select *
from table1
    left join 
    (
         select id from table2 
         where status in ('open', 'close')
         group by id

    ) as table2
        on table1.id = table2.id

这看起来很漂亮,但我现在似乎无法想出更好的东西。否则,您可以使用DISTINCT

select DISTINCT table1.*, table2.stuff
FROM Table1
    LEFT JOIN Table2
        on Table2.Id = Table1.Id and Table2.status in  ('Close', 'Open')

答案 1 :(得分:0)

关键是DISTINCT声明。

SELECT DISTINCT Table1.* FROM Table1 
     LEFT JOIN Table2 ON Table2.Id = Table1.Id 
                      AND Table2.status in  ('Close', 'Open')