2014-09-23 44 views
0

我有一個表像下面這樣,我需要的結果是這樣的,當我運行查詢SQl的 - 選擇列,並將它們組合

結果

title | count 
---------------- 
foo | 3 
bar | 2 

customer_id | title 
------------------- 
55   | foo 
22   | foo 
55   | bar <-- duplicate 
23   | bar 
55   | bar <-- duplicate 
23   | foo 

UPDATE謝謝大家的支持ick響應!

+0

[與結果組]的可能重複(http://stackoverflow.com/questions/5156349/group-by-with-results) – bodi0 2014-09-23 09:27:36

+0

很多人忽視了「重複」註釋。下次在描述你的問題的時候會更加明確。 – GolezTrol 2014-09-23 09:32:01

+0

我會,很難當你不知道你在找什麼! – SinisterGlitch 2014-09-23 09:34:43

回答

3

關鍵是要算distinct客戶ID,這樣你就不會算雙富客戶55

如果需要,你可以訂購的結果通過算過,或你可以忽略order by條款。

select 
    title, 
    count(DISTINCT customerid) as `count` 
from 
    yourTable 
group by 
    title 
order by 
    `count` desc 
+0

謝謝你,我的整個邏輯都在完成這些查詢的同時完成。現在我知道將來會做什麼! – SinisterGlitch 2014-09-23 09:34:06

-1

對於SQL Server,你可以這樣做。

select 
    t.title  , 
    count(*) 
from your_table as t 
group by 
    t.title 
order by count(*) DESC 
+0

這不會給出給定示例數據的請求結果。 – GolezTrol 2014-09-23 09:33:02

0

這是那麼容易,因爲這樣的:

select A.title, count(*) as count -- an usual count(*) 
from 
(select distinct customer_id, title -- this query removes the duplicates 
from table) A 
group by A.title -- an usual group by 
相關問題