简体   繁体   English

SELECT DISTINCT 在 SQL 服务器 2014 中的一列上

[英]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.我使用DistinctTopOrder 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您可以将maxgroup 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM