SQL Count()列值

时间:2014-08-29 14:13:45

标签: mysql sql count

我有以下源表:

pid | code
----------
1      P2
2      P2
3      P3
4      P1
5      P2
6      P1

现在,我想获取每个代码存在多少次的信息:

code | count
------------
P2      3
P1      2
P3      1

所以我想计算代码列中的值并将其分配给不同的可用代码值集。最后,我想按计数编号。

2 个答案:

答案 0 :(得分:3)

SQL Fiddle

SELECT t.code, COUNT(*) AS `count`
FROM MyTable t
GROUP BY t.code
ORDER BY COUNT(*) DESC

答案 1 :(得分:1)

DECLARE @testTable table (pid  int
                     ,code varchar(2)
)

insert into @testTable values (1, 'P2')
insert into @testTable values (2, 'P2')
insert into @testTable values (3, 'P3')
insert into @testTable values (4, 'P1')
insert into @testTable values (5, 'P2')
insert into @testTable values (6, 'P1')


SELECT CODE, COUNT(1) AS [COUNT]
FROM @testTable 
GROUP BY CODE
ORDER BY [COUNT] DESC