简体   繁体   English

从数据表中选择每个ID的顶部条目-SQL

[英]Select top entry per ID from data table - SQL

Assuming I have the following data table: 假设我有以下数据表:

ID       VALUE 
---      ------- 
123      a
123      b
456      c
456      d
789      e

How can I get the output to only select the top entry per ID, assuming the data is already ordered. 假设数据已经订购,如何获取输出以仅选择每个ID的顶部条目。 Ie, I need the data to show: 即,我需要显示以下数据:

ID       VALUE
---      -------
123      a
456      c
789      e

SQL tables represent unordered sets. SQL表表示无序集。 There is no ordering to the table, unless you have a column that specifies the ordering. 该表没有顺序,除非您有指定顺序的列。

This is fundamental in SQL. 这是SQL的基础。 Let me assume you have an ordering column. 让我假设您有一个订购专栏。 Then you can do: 然后,您可以执行以下操作:

select t.*
from t
where t.ordcol = (select max(t2.ordcol) from t t2 where t2.id = t.id);

Also you can add the ordering dynamically, 您也可以动态添加订单,

eg 例如

select * from 

(select id, value, dense_rank() OVER (ORDER BY value asc) as myrank from #mytable ) aa

where myrank=1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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