views:

47

answers:

2

When I run query number 1:

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

I get the following results:

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

This is fine, except, I want each of instance of a counted name to appear with its respective ID as seen in the result of query number 2:

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

Which produces the following results:

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

Is there a query I can run that will return the id and name from query number 2 and the corresponding count from query number 1 in each row as shown below?

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  A: 

Try this:

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 
Graphain
+1: You were first
OMG Ponies
Thanks but only because you edited his question I assume
Graphain
Occupational hazard
OMG Ponies
Awesome, thanks! One tiny edit; the clause "WHERE state like 'OR'" belongs in the subquery as well.
Keyslinger
@Keyslinger - amended thanks. You could probably move the having into the inner where too if you liked
Graphain
+1  A: 

You can use:

   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
OMG Ponies