2014-08-29 61 views
1

我有以下源表:SQL計數()列的值

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

現在,我想要得到的信息,每個代碼有多少次存在:

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

所以我想算代碼列中的值並將其分配給不同的可用代碼值集。最後,我想按計數編號。

+0

你爲什麼都指望括號首先所有的MySQL和第二它不是一個保留字? – Mihai 2014-08-29 14:18:39

+0

[SQL:如何獲得列中每個不同值的計數?]的可能重複(http://stackoverflow.com/questions/7053902/sql-how-to-get-the-count-of-each-不同的值在列) – 2014-08-29 14:36:01

回答

3

SQL Fiddle

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

這正是我需要的。謝謝! – 17nxo 2014-08-29 14:31:56

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 
+0

'[COUNT]'不起作用。您需要改爲使用後面的勾號。 'ORDER BY [COUNT] DESC'也不行,你需要使用'ORDER BY COUNT(1)DESC'。 – Linger 2014-08-29 14:27:28

+0

對我很好 – Deiwys 2014-08-29 14:29:23