当前位置: 代码迷 >> Sql Server >> 简单的表查询语句
  详细解决方案

简单的表查询语句

热度:98   发布时间:2016-04-27 16:03:54.0
求一个简单的表查询语句
有一个表,这个表X只有一列,假设为col并且只有两个值:true,false
现在的要求是求出来true,false 各有多少行,
在这里我写了一个,不好:
Select count(*) as tr, (Select count(*) from T where col= false) as fa from T where col= true


------解决方案--------------------
select x , count(*) from tb group by x
------解决方案--------------------
select col , count(*) from x group by col
------解决方案--------------------
SQL code
create table x(col varchar(10))insert into x values('true') insert into x values('true') insert into x values('true') insert into x values('true') insert into x values('false') insert into x values('false') goselect col , count(*) cnt from x group by col--drop table col/*col        cnt         ---------- ----------- false      2true       4(所影响的行数为 2 行)*/
------解决方案--------------------
只有两种的话,不用group也行:
SQL code
select col='true', cnt=count(1) from tb where col='true'union allselect col='false', cnt=count(1) from tb where col='false'
------解决方案--------------------

select col, [count] = case col when 'true' then count(col) else count(col) end 
from X
group by col
------解决方案--------------------
SQL code
select col,count(1) from x group by col
  相关解决方案