【问题标题】:Boolean Logic in Select Statement [duplicate]Select 语句中的布尔逻辑
【发布时间】:2014-09-02 05:31:17
【问题描述】:

如何在查询运行时在 select 语句中实现布尔逻辑?

SELECT t.[Key]
      ,t.[Parent_Key]
      ,t.[Parent_Code]
      ,t.[Code]
      ,t.[Desc] 
      ,t.[Point]
      ,[isChild] -- If Point > 2, then true, if Point == 1 Then false   
      ,t.[By] 
      ,t.[On]
FROM [db].[stats] t WHERE t.[Parent_Key]= @tmpParameter

我想做一些逻辑来根据 t.[Point] 确定 [isChild] 布尔值

【问题讨论】:

标签: sql-server-2008 sql


【解决方案1】:
SELECT t.[Key]
      ,t.[Parent_Key]
      ,t.[Parent_Code]
      ,t.[Code]
      ,t.[Desc] 
      ,t.[Point]
      ,CASE WHEN t.[Point] > 2 THEN 1 ELSE  
            CASE WHEN t.[Point] = 1 THEN 0 ELSE NULL END 
       END AS [isChild]
      ,t.[By] 
      ,t.[On]
FROM [db].[stats] t WHERE t.[Parent_Key]= @tmpParameter

请注意,当 t.[Point]

【讨论】:

    【解决方案2】:

    凯斯是你的朋友...

     SELECT Key, Parent_Key, Parent_Code, Code, Desc, point, 
         case when point > 2 then 1 
              when point = 1 then 0 end isChild, 
         [By], [On]
     FROM db.stats  
     WHERE Parent_Key= @tmpParameter
    

    【讨论】:

      【解决方案3】:

      使用case语句:

      SELECT t.[Key]
            ,t.[Parent_Key]
            ,t.[Parent_Code]
            ,t.[Code]
            ,t.[Desc] 
            ,t.[Point]
            ,CASE t.[Point] WHEN 1 THEN FALSE WHEN 2 THEN TRUE END as [isChild]
            ,t.[By] 
            ,t.[On]
      FROM [db].[stats] t WHERE t.[Parent_Key]= @tmpParameter
      

      【讨论】:

        【解决方案4】:

        你可以使用 CASE 语句

        SELECT t.[Key]
          ,t.[Parent_Key]
          ,t.[Parent_Code]
          ,t.[Code]
          ,t.[Desc] 
          ,t.[Point]
          ,CASE 
          WHEN t.[Point] THEN true 
          else false
          END as isChild
          ,t.[By] 
          ,t.[On]
        FROM [db].[stats] t WHERE t.[Parent_Key]= @tmpParameter
        

        【讨论】:

          猜你喜欢
          • 2018-08-10
          • 2018-06-15
          • 2011-09-30
          • 1970-01-01
          • 1970-01-01
          • 2020-07-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多