Please help me design this SQL query

Started by
12 comments, last by Wan 14 years, 5 months ago
Quote:Original post by Wan
I think this should work (untested):
SELECT  DISTINCT address, COUNT(DISTINCT(surname))FROM  Table1GROUP BY  address
In the first column we're selecting all distinct addresses, in the second column we count the number of distinct surnames within a particular address.


+1 (well, the syntax is COUNT(DISTINCT surname) and the GROUP BY makes the first DISTINCT pointless, but you get the idea).
Advertisement
I'm not sure if I understood you correctly but:

SELECT DISTINCT T1.surname, (select count(*) FROM [Table] AS T2 WHERE T2.surname=T1.surname) AS num_addresses FROM [Table] AS T1
[size="2"]I like the Walrus best.
Thank you Wan, that works fine!

Is it a happy side-effect of GROUP BY that DISTINCT(surname) limits its scope to the address at that row, or is that exactly what GROUP BY was designed for?
Quote:Original post by ToohrVyk
+1 (well, the syntax is COUNT(DISTINCT surname) and the GROUP BY makes the first DISTINCT pointless, but you get the idea).

Um yeah. Blame incremental development. :)

Quote:Original post by spraff
Is it a happy side-effect of GROUP BY that DISTINCT(surname) limits its scope to the address at that row, or is that exactly what GROUP BY was designed for?

In this case the latter. Consider this obvious example:
SELECT  COUNT(DISTINCT(surname))FROM  Table1

This will count the number of distinct surnames in the table, right?
But now we would like to split (group) them by address:
SELECT  COUNT(DISTINCT(surname))FROM  Table1GROUP BY  address

Profit!

This topic is closed to new replies.

Advertisement