SQL中聚合函数+Case 的使用

原文链接: https://www.cnblogs.com/linyechengwei/archive/2011/10/12/2208956.html

怎么把两个相同的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  end)  as  ' 可用 ',
count( case  when state = 0  then  1  else  0  end)  as  ' 不可用 ',
count( 1)  as  ' 总人数 '
from users

猜你喜欢

转载自blog.csdn.net/yelin042/article/details/101051999