I want to be able to select two distinct from col1 and col2 ordered by id.
I'm struggling to do this because when I write the following SQL query...
SELECT DISTINCT col1, col2
FROM table
ORDER BY id
I can't ORDER BY id because it's not in the SELECT statement but if I put id in the SELECT statement it will take the DISTINCT id, col1 and col2. Which is basically the whole table as it is since the id column is unique.
How do I do this?
您可以使用聚合,并在order by
子句中放置一个聚合函数:
select col1, col2 from mytable group by col1, col2 order by min(id) limit 10
This is one way to do it:
select A.col1, A.col2
from
(select id, col1, col2
from Tablet
order by id) A
left join
(select min(id) id2, col1, col2
from Tablet
GROUP BY COL1, COL2) B
on A.COL1 = B.COL1 AND A.COL2=b.COL2
where A.id = B.id2
LIMIT 4;
Here is the DEMO
If the task means "if there are duplicates by (col1, col2)
then remove all such duplicates except one with the greatest id
value", then
SELECT DISTINCT MAX(id) OVER (PARTITION BY col1, col2) id, col1, col2
FROM sourcetable
ORDER BY id DESC /* not sure in this point */
LIMIT 10
PS. Why "greatest"? because of
So it should eliminate row 3 and NOT row 4 as it is duplicated.
If the record with the least id
value needed then replace MAX() to MIN().
PPS. It seems the real task is "Show last 10 original messages from chat history".
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.