zoukankan      html  css  js  c++  java
  • 在where条件中使用CASE WHEN 语句

    CREATE TABLE TB_Test_Report
    (
    id  int identity,
    stateid int,
    userid  int,
    username varchar(64)
    )
    
    go
    
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (20,1,'a')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (10,2,'b')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (20,2,'b')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (10,1,'a')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (10,1,'a')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (10,3,'c')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (10,3,'c')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (20,1,'c')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (10,1,'a')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (10,1,'A')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (30,1,'a')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (30,1,'b')
    INSERT INTO TB_Test_Report (stateid,userid,username) VALUES (30,1,'c')
    go
    
    
    /**
     已知语句 select * from TB_Test_Report where stateid in (10,20)
     要求在语句后面增加条件(加入 and  或者 or  或者 表达式)
     查询出,所有stateid =10 和 (stateid=20 并且userid = 2) 的记录
     */
     
    SELECT *
    FROM   TB_Test_Report
    WHERE  stateid IN ( 10, 20 )
           AND ( CASE
                   WHEN stateid = 20
                        AND userid <> 2 THEN 0
                   ELSE 1
                 END ) = 1 
                 
    
    
     

    此类问题关键在于

    1. CASE WHEN 可以用于WHERE
    2. CASE WHEN 中可以使用AND 进行逻辑判断
    3. CASE WHEN 表达式最终由返回值
  • 相关阅读:
    ios 应用程序之间的跳转(内置程序的实现)
    iOS手势UIGustureRecognizer
    动画学习之Animating Views with Blocks
    get 和post 方式请求数据
    通过路径添加图片
    contentSize、contentInset和contentOffset区别
    bzoj1055 [HAOI2008]玩具取名 区间DP
    bzoj1025 [SCOI2009]游戏 动态规划
    POJ2299 树状数组求逆序对
    洛谷1525 关押罪犯NOIP2010 并查集
  • 原文地址:https://www.cnblogs.com/songr/p/5588181.html
Copyright © 2011-2022 走看看