SQL查询:选择所有位置,如果x = 1,则为y

时间:2013-07-24 12:35:54

标签: sql sql-server sql-server-2005

我想选择所有列但是如果fuel = 1则开始日期> '1 oct 2013'否则,如果燃料= 0,则开始日期> '九月一日'。

使用SQL Server 2005。

我试过了..

SELECT * FROM   EntitlementEpisode
WHERE
    IF EnFuel = 1
        THEN
            IF
                BEGIN
                    [EnEpisodeStart] > 
                    (SELECT TOP 1 [BeYearStart] 
                    FROM [BenefitYear] ORDER BY [BeId] desc)
                END
            ELSE IF EnFuel = 0
       THEN
            IF
                 BEGIN
                      [EnEpisodeStart] > 
                      CONVERT(VARCHAR(30), '1 OCT' + YEAR(GETDATE()))
            END

这是正确的解决方法吗?

2 个答案:

答案 0 :(得分:3)

使用二元运算符的强度......!

SELECT * 
FROM   EntitlementEpisode
WHERE
   (EnFuel=1 AND EnEpisodeStart] > 
                (SELECT TOP 1 [BeYearStart] 
                FROM [BenefitYear] ORDER BY [BeId] desc))

   OR

   (EnFuel=0 AND [EnEpisodeStart] > 
                  CONVERT(VARCHAR(30), '1 OCT' + YEAR(GETDATE())))

答案 1 :(得分:0)

这样的东西
SELECT  * 
FROM    EntitlementEpisode
WHERE   (EnFuel = 1 AND [EnEpisodeStart] > (SELECT TOP 1 [BeYearStart] FROM [BenefitYear] ORDER BY [BeId] desc)
OR      (EnFuel = 0 AND [EnEpisodeStart] > CONVERT(VARCHAR(30), '1 OCT' + YEAR(GETDATE())))