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
  • 相关阅读:
    (笔记)电路设计(十三)之振荡电路的应用
    (笔记)电路设计(十二)之高速数字系统滤波电容的设计应用
    爬楼梯问题 leetcode70
    偏函数
    柯里化
    插入排序
    选择排序
    冒泡排序
    解包(封装和解构)、丢弃变量
    数据类型之集合
  • 原文地址:https://www.cnblogs.com/linyechengwei/p/2208956.html
Copyright © 2011-2022 走看看