[英]SELECT DISTINCT on one column in SQL Server 2014
In SQL Sever 2014
, I have a table like this:在
SQL Sever 2014
中,我有一个这样的表:
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
。
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.我使用
Distinct
, Top
, Order by
但它不起作用。 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:您需要
max()
聚合 function 但随后您必须按其他列对结果集进行group by
:
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
您可以将
max
与group by
一起使用
select max(tag_id)tag_id,prd_id,prod_nm
from mytable
group by prd_id,prod_nm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.