zoukankan      html  css  js  c++  java
  • SQL中聚合函数+Case 的使用

    怎么把两个相同的sql语句用多表连接的方法给连接起来呢?
    比如users表中,state字段,表示用户状态,1表示可用,0表示不可用,如何在一张表中显示出可用人数与不可用人数?
    表中还有字段userid,username

    1、使用 sum + case

    declare  @t  table 
    (userid  int,username  varchar( 8),state  int)
    insert  into  @t
    select  1, ' zhangsan ', 0  union  all
    select  2, ' lisi ', 1  union  all
    select  3, ' wangwu ', 1  union  all
    select  4, ' liuliu ', 0  union  all
    select  5, ' chenqi ', 0  union  all
    select  6, ' wuba ', 0

    declare  @可用人数  int, @不可用人数  int
    select 
    @可用人数 = sum( case state  when  0  then  1  else  0  end),
    @不可用人数 = sum( case state  when  1  then  1  else  0  end)
    from  @t

    select  *, @可用人数  as 可用人数, @不可用人数  as 不可用人数
    from  @t
    /*
    userid      username state       可用人数        不可用人数
    ----------- -------- ----------- ----------- -----------
    1           zhangsan 0           4           2
    2           lisi     1           4           2
    3           wangwu   1           4           2
    4           liuliu   0           4           2
    5           chenqi   0           4           2
    6           wuba     0           4           2
    */

    2、使用count + case

    select  count( case  when state = 1  then  1  else  0  endas  ' 可用 ',
    count( case  when state = 0  then  1  else  0  endas  ' 不可用 ',
    count( 1as  ' 总人数 '
    from users
  • 相关阅读:
    while和do while习题
    Flexigrid折行显示问题
    【Cocos2d-x游戏引擎开发笔记(25)】XML解析
    ruby简单的基本 6
    原因好消息: PSP游戏自己主动算法设计(两)
    《约会专家》拖车【约会宝典】总结
    C++在stack的deque实现
    hdu 4869
    SQL Server 2008杀数据库连接
    BestCoder-Round#33
  • 原文地址:https://www.cnblogs.com/linyechengwei/p/2208956.html
Copyright © 2011-2022 走看看