tags:

views:

90

answers:

4

Hi,

I have a table - something like:

A|B
1|1
1|2
1|3
2|1
2|3
2|4
2|5
3|5

My query returns the distinct values in A if they coincide with a value in B of 1 or 2 - so

A
1
2

I am trying to also return the original count of the 1's and 2's in column A - to get something like

A|Count
1|3
2|4

Is there a simple way to get this count please? However, the COUNT (A) returns the number of A's coinciding with the initial WHERE statement:

A|Count
1|2
2|1

Thanks!

+2  A: 

My SQL might be a bit rusty, but I think you can do:

SELECT A, count(*) AS Count FROM MyTable WHERE B IN (1, 2) GROUP BY A;
rally25rs
Note that I'm not 100% sure this syntax works in MySQL, but it would work in Oracle, and I think its close to ANSI standard SQL.
rally25rs
A: 
SELECT t1.A, COUNT(DISTINCT t1.B)
FROM MyTable t1 JOIN MyTable t2 ON (t1.A = t2.A)
WHERE t2.A = t2.B
GROUP BY t1.A;
Bill Karwin
Why the DISTINCT - or JOIN?
Jonathan Leffler
There might be more than one value of t2.A = t2.B.
Bill Karwin
A: 

Similar to Bill Karwin's answer:

SELECT
  A,
  Counted.CountOfB
FROM
  MyTable
  INNER JOIN (
    SELECT A, COUNT(B) AS CountOfB
    FROM   MyTable
    GROUP BY  A
  ) Counted ON Counted.A = MyTable.A
WHERE
  {your filter for MyTable}
Tomalak
+1  A: 

Another way:

SELECT a, (SELECT count(*) FROM t t2 WHERE t2.a = t.a) a_count
FROM t
WHERE b IN (1,2)
GROUP BY a
araqnid
Thanks! Worked really well :)