简体   繁体   中英

MySQL group by two columns

I have a mysql table with the fields id, name, address. Some entries have identical names but different addresses; some have identical addresses but different names.

I want to get a list including one entry at most for each unique address and one entry at most for each unique name.

If I could do a group by name then put the results in a temp table and then select again and do a group by address, then I would get exactly what i want - but that seems too complicated.

And doing a "group by name,address" will not give me what I am looking for - that would include entries for all different combinations of name,address whereas I want one entry for each name and one for each address. Thanks for your help!

There's probably a nicer way to do this, and I'm making some assumptions about what you want, but you could try something like this:

SELECT Name, '' AS Address, Count(Address) AS RowCount
  FROM TableName
  GROUP BY Name
UNION
SELECT '' AS Name, Address, Count(Name) AS RowCount
  FROM TableName
  GROUP BY Address

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM