代码之家  ›  专栏  ›  技术社区  ›  user1447679

为什么这个SQL case语句的行为类似于OR语句?

  •  1
  • user1447679  · 技术社区  · 7 年前

    declare @RentalId int = 1
    
    SELECT 
         r.RentalId
        ,r.[Name]
        ,rt.TypeId
    
    
    FROM dbo.Rental r
    LEFT JOIN dbo.RentalRateType rt ON (
        r.RentalId = rt.RentalId
        AND rt.TypeId = (
            case when rt.TypeId = 6 and coalesce(rt.[Max], rt.[Min]) is not null then 6
             when rt.TypeId = 1 and coalesce(rt.[Max], rt.[Min] is not null then 1 
            else -1 end
    ))
    WHERE r.RentalId = @RentalId
    

    我试图返回单个记录/行。有关的特定租金在 dbo.RentalRateType 表,当我运行上面的查询时,我得到2个结果,但我希望它在 case where

    基本上,最终用户可以填写多种费率类型,比您在本例中看到的要多,而且每种类型都有一个优先级。6是示例中的最高优先级。

    所以我得到这个结果:

    RentalId |   Name   | TypeId
    ----------------------------
    1          Super Car  6    
    1          Super Car  1
    

    但是如果类型(6)存在,我希望只返回上面的第一行。

    case when 1=2 then 6
         when 1=1 then 1 
         else -1 end
    

    当我在这里的时候,我愿意以一种更有效的方式来处理这个问题。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Adrian Maxwell    7 年前

    使用 apply 相反,这些是获取“前n个”查询的有效方法:

    SELECT
        r.RentalId
      , r.[Name]
      , oa.TypeId
    FROM dbo.Rental r
    OUTER APPLY (
            SELECT TOP (1)
                rt.TypeId
            FROM dbo.RentalRateType rt
            WHERE r.RentalId = rt.RentalId
            ORDER BY
                rt.TypeId DESC
        ) oa
    WHERE r.RentalId = @RentalId