通过应用任何条件(if或case)选择行

时间:2016-07-12 12:56:48

标签: sql sql-server tsql

我有一组记录,如下所示:

Id  Name  status  date

1    xx     1      2016-06-27 14:05:17.447
2    yy     2      2016-06-27 14:05:17.447
3    zz     1      2016-06-27 14:05:17.447
4    aa     2      2016-06-27 14:05:17.447
5    bb     2      2016-06-27 14:05:17.447

我想从上面选择所有行但是 对于status = 1的行,我想应用

的条件
select if status=1 and date<=getdate

我该怎么做?

3 个答案:

答案 0 :(得分:1)

select
Id,
Name,
case when   status =1 and date<getdate() then 'I want to select this row' else I don't want to select this row end as statuss 
,date
from
yourtable

更新:根据您的编辑,您需要在where子句

中应用您的条件
select * from yourtable
where status=1 and date<getdate()

答案 1 :(得分:1)

我能想到的最简单的方法,除非状态可以为空:

SELECT Id, Name, Status, Date
FROM TableName
WHERE status <> 1 
OR date <= getdate()

如果它可以为空,你可以这样做:

SELECT Id, Name, Status, Date
FROM TableName
WHERE ISNULL(status, 0) <> 1 
OR date <= getdate()

答案 2 :(得分:1)

试试这个:

CREATE TABLE #Status
    (
      Id INT
    , Name CHAR(2)
    , status INT
    , date DATETIME
    );

INSERT  INTO #Status
        ( Id, Name, status, date )
VALUES  ( 1  -- Id - int
          , 'xx'  -- Name - char(2)
          , 1  -- status - int
          , '2016-06-27 14:05:17.447'  -- date - datetime
          ),
        ( 2  -- Id - int
          , 'yy'  -- Name - char(2)
          , 2  -- status - int
          , '2016-06-27 14:05:17.447'  -- date - datetime
          ),
        ( 3  -- Id - int
          , 'zz'  -- Name - char(2)
          , 1  -- status - int
          , '2016-06-27 14:05:17.447'  -- date - datetime
          ),
        ( 4  -- Id - int
          , 'aa'  -- Name - char(2)
          , 2  -- status - int
          , '2016-06-27 14:05:17.447'  -- date - datetime
          ),
        ( 5  -- Id - int
          , 'bb'  -- Name - char(2)
          , 2 -- status - int
          , '2016-06-27 14:05:17.447'  -- date - datetime
          ),
        ( 6  -- Id - int
          , 'cc'  -- Name - char(2)
          , 1 -- status - int
          , '2016-07-27 14:05:17.447'  -- date - datetime
          );

SELECT  *
FROM    #Status;
WITH    cte
          AS ( SELECT   *
               FROM     #Status
               WHERE    status <> 1
             ) ,
        cteStatus1
          AS ( SELECT   *
               FROM     #Status
               WHERE    status = 1
                        AND date <= GETDATE()
             )
    SELECT  *
    FROM    cte
    UNION
    SELECT  *
    FROM    cteStatus1;