我有一个如下所示的表格,当我运行查询时,我需要结果是这样的
结果
title | count
----------------
foo | 3
bar | 2
表格
customer_id | title
-------------------
55 | foo
22 | foo
55 | bar <-- duplicate
23 | bar
55 | bar <-- duplicate
23 | foo
更新谢谢大家的快速回复!
答案 0 :(得分:3)
诀窍在于计算distinct
客户ID,因此您不会为客户55计算双Foo。
如果需要,您也可以按该计数订购结果,或者您可以省略order by
条款。
select
title,
count(DISTINCT customerid) as `count`
from
yourTable
group by
title
order by
`count` desc
答案 1 :(得分: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
答案 2 :(得分:-1)
对于SQL Server,您可以这样做。
select
t.title ,
count(*)
from your_table as t
group by
t.title
order by count(*) DESC