日期:2014-05-18  浏览次数:20505 次

求一个简单的表查询语句
有一个表,这个表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') 
go

select col , count(*) cnt from x group by col

--drop table col

/*
col        cnt         
---------- ----------- 
false      2
true       4

(所影响的行数为 2 行)
*/

------解决方案--------------------
只有两种的话,不用group也行:
SQL code
select col='true', cnt=count(1) from tb where col='true'
union all
select 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