I need to get max X.Id from each Specific kind, Example:
Table:
Id | Kind
---------
1 | 20
2 | 20
3 | 15
4 | 15
---------
My query needs to get the Ids 2 and 4, because my kinds are 15 and 20, this is my current query:
SELECT max(Id)
FROM X
WHERE KIND = 15 or KIND = 20
But this query only returns id 4. I need 2 and 4, the max Id for each kind. I don't want to run more than one query. With subqueries and more than one query I know how to do.
I would like to know how to do with only one query.
Can anyone help me?
You need to add GROUP BY
clause:
SELECT max(Id) as ID
FROM X
WHERE KIND = 15 or KIND = 20
GROUP BY KIND
The result will be:
ID
-----
2
4
Suggestion
You can use IN
for simplicity:
SELECT max(Id) as ID
FROM X
WHERE KIND IN (15,20)
GROUP BY KIND
You have to use group by kind
SELECT max(Id)
FROM X
WHERE KIND = 15 or KIND = 20
group by Kind
order by 1
Create table Test (Id int, Kind int)
Insert Test(Id,Kind) Values (1, 20)
Insert Test(Id,Kind) Values (2, 20)
Insert Test(Id,Kind) Values (3, 15)
Insert Test(Id,Kind) Values (4, 15)
Insert Test(Id,Kind) Values (5, 10)
Insert Test(Id,Kind) Values (6, 10)
Select * from Test
Select MAX(Id) from Test
Where Kind in (20, 15)
Group by Kind
Select MAX(Id) from Test
Group by Kind
Having Kind in (20, 15)
Drop Table Test
SELECT max(Id), KIND
FROM X
Group by KIND
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.