In SQL Sever 2014
, I have a table like this:
tag_id prd_id prod_nm
--------------------------------------
1 1 apple
2 1 apple
3 1 apple
4 2 banana
5 2 banana
6 3 tomato
7 3 tomato
8 4 cabbage
9 5 melon
And I want to get the highest tag_id
for each product.
tag_id prd_id prod_nm
------------------------------
3 1 apple
5 2 banana
7 3 tomato
8 4 cabbage
9 5 melon
I used Distinct
, Top
, Order by
but it isn't working. How can I get this result?
You need the max()
aggregate function but then you have to do a group by
to group the result-set by the other columns:
SELECT max(tag_id) AS tag_id, prd_id, prod_nm
FROM table
GROUP BY prd_id, prod_nm
You can use max
with group by
select max(tag_id)tag_id,prd_id,prod_nm
from mytable
group by prd_id,prod_nm
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.