Sql Query获取与特定条件匹配的总行数和总行数

时间:2011-01-12 06:45:57

标签: mysql

好的,这是我的表格的样子

------------------------------------------------
id                     type
-----------------------------------------------
1                      a
2                      b
3                      a
4                      c
5                      c
7                      a
8                      a
------------------------------------------------

现在,我需要一个可以给我输出的查询......

-----------------------------------------------------------------
count(*)   |   count(type=a)   | count(type=b)  | count(type=c)
-----------------------------------------------------------------
8                  4                 1               3
------------------------------------------------------------------

我只知道使用count(*)得到总集合,但是如何做剩下的

3 个答案:

答案 0 :(得分:8)

SELECT 
COUNT(*),
COUNT(CASE WHEN type='a' THEN 1 END) as count_a,
COUNT(CASE WHEN type='b' THEN 1 END) as count_b,
COUNT(CASE WHEN type='c' THEN 1 END) as count_c,
FROM table1;

//or you can do 
SELECT type, COUNT(*) 
FROM table1 
GROUP BY type WITH ROLLUP

在后一种情况下,您将获得结果:

a | 4
   b | 1
   c | 3
   null | 8

答案 1 :(得分:1)

您可以尝试类似

的内容
SELECT  COUNT(*) Total, 
        SUM(CASE WHEN type='a' THEN 1 ELSE 0 END) as CountOfA, 
        SUM(CASE WHEN type='b' THEN 1 ELSE 0 END) as CountOfB, 
        SUM(CASE WHEN type='c' THEN 1 ELSE 0 END) as CountOfC, 
FROM    Table

答案 2 :(得分:0)

select count(*),type
from [TableName]
Group By Type