SELECT with COUNT in single query I have a table that I get names and counts from but do it in 2
seperate queries. I have to imagine it's possible in 1 cool query.
Table:
Name Value Date
John A 2007-10-30
John B 2007-10-30
John C 2007-10-30
John D 2007-10-30
John E 2007-10-30
Mark A 2007-10-31
Lucy C 2007-10-31
Lucy D 2007-10-31
Mark D 2007-11-01
Hank A 2007-11-01
Hank D 2007-11-02
What I want from this is:
John 3
Mark 1
Lucy 1
Basically, I want a count per distinct Name of each Value that is
"given" to someone else. Right now I do this with 2 queries:
Doing this in perl, first I use this to populate an array of Value's:
SELECT Value FROM TABLE GROUP BY Value HAVING COUNT(*) > 1 ORDER BY
Value, Date
then I use this to cycle through each Value to get the Names
SELECT Name FROM TABLE WHERE Value=? ORDER BY Date DESC
I increment a counter (hash) for each Name except for the first row,
since the last guy to get it didn't give it to someone else.
Make sense? |