简体   繁体   中英

Select distinct name with random id

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?

Arbitrarily choosing to return the minimum id per name.

SELECT name, MIN(id)
    FROM YourTable
    GROUP BY name

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
select ID, name from table group by name;

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