Get one record per unique column value

元气小坏坏 提交于 2019-12-11 11:16:52

问题


I have a table that list system licences, multiple licences for each system (the expired ones and existing ones). I've only posted two columns in this question as they're the only important ones.

| id | systemid | 
|  1 |        1 |
|  2 |        1 |
|  3 |        2 |
|  4 |        2 |
|  5 |        3 |
|  6 |        3 |

I need to get the rows with the id of 2, 4 and 6.

I need to collect 1 record for each systemid and it has to be the earliest (youngest) record, so in this case, the record with the highest id. I've been exploring GROUP BY, ORDER BY and LIMIT but I'm not producing the result I'm after. How do you collect one record for each individual value in one column and make sure it's the record with the highest id?

I KNOW this is wrong, but it's what I'm currently starring at:

SELECT * FROM licences GROUP BY systemid ORDER BY id DESC LIMIT 1


回答1:


SELECT max(id), systemid FROM table GROUP BY systemid

Note that with a GROUP BY, all columns you select must either be in the GROUP BY clause or wrapped in an aggregating function, like max, min, sum, or average.




回答2:


This will grab the highest id per systemid.

SELECT MAX(id), systemid
FROM ...
GROUP BY systemid


来源:https://stackoverflow.com/questions/23121100/get-one-record-per-unique-column-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!