Reputation: 372
I have a table with an id and a name (an a bunch of other stuff not relevant for this query). Now I need an SQL statement that returns one row per distinct name and in that row I need the name and one id (can be any id).
The table is looking something like this:
id | name
---+-----
1 | a2
2 | a2
3 | a4
4 | a4
5 | a2
6 | a3
btw. using Postgres 8.4
Tried various combinations of grouping or joining with self. Is this even possible without creating extra tables?
Upvotes: 2
Views: 1887
Reputation: 13083
You may look at PostgreSQL wiki. It shows how to select random rows.
You may use random()
function to select random rows using ORDER BY
clause of SELECT
. Example:
SELECT id FROM mytable ORDER BY random()
You can then use GROUP BY
to select distinct names. You may need to limit results using LIMIT
clause. So the query looks something like this:
SELECT id, name FROM table_name GROUP BY name ORDER BY random() LIMIT 1
Upvotes: 0
Reputation: 135818
Arbitrarily choosing to return the minimum id per name.
SELECT name, MIN(id)
FROM YourTable
GROUP BY name
Upvotes: 4