SQL:单个结果行中的组计数

时间:2010-07-12 01:12:28

标签: sql mysql count group-by

当我运行第1号查询时:

SELECT id, name, COUNT(name) AS count 
  FROM markers 
 WHERE state like 'OR' 
group by named

我得到以下结果:

id  name                count
14  Alsea               2
76  Applegate Valley    1
3   Ashland             9
64  Beaver              1
26  Bend                1
10  Carlton             2

这没关系,除了我希望每个计数名称的实例都出现其各自的ID,如查询编号2的结果所示:

SELECT id, name, COUNT(name) AS count 
  FROM markers 
WHERE state like 'OR' 
group by name, id

产生以下结果:

id  name                count
14  Alsea               1
28  Alsea               1
76  Applegate Valley    1
3   Ashland             1
13  Ashland             1
16  Ashland             1
20  Ashland             1
22  Ashland             1
43  Ashland             1
48  Ashland             1
51  Ashland             1
72  Ashland             1
64  Beaver              1
26  Bend                1
10  Carlton             1
27  Carlton             1

我是否可以运行一个查询,它将返回查询号2中的id和名称以及每行中查询号1的相应计数,如下所示?

id  name                count
14  Alsea               2
28  Alsea               2
76  Applegate Valley    1
3   Ashland             9
13  Ashland             9
16  Ashland             9
20  Ashland             9
22  Ashland             9
43  Ashland             9
48  Ashland             9
51  Ashland             9
72  Ashland             9
64  Beaver              1
26  Bend                1
10  Carlton             2
27  Carlton             2

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT id, name, 
 (SELECT COUNT(name) 
   FROM markers im 
   WHERE state like 'OR' 
   GROUP BY name 
   HAVING im.name=m.name) as count
FROM markers m 
WHERE state like 'OR' 
GROUP BY name, id 

答案 1 :(得分:1)

您可以使用:

   SELECT t.id,
          t.name,
          COALESCE(x.cnt, 0) AS count
     FROM MARKERS t
LEFT JOIN (SELECT m.name,
                  COUNT(m.*) AS cnt
             FROM MARKERS m
            WHERE m.state LIKE 'OR'
         GROUP BY n.name) x ON x.name = t.name
     WHERE t.state LIKE 'OR'
  GROUP BY t.id, t.name