简体   繁体   English

从条目组中选择一个不同的行

[英]Selecting one distinct row from group of entries

ID  TYPE     DATE
1    A    01/02/2019
1    B    01/21/2019
1    C    02/03/2019
2    A    01/04/2019
2    C    01/29/2019
3    A    01/14/2019
3    B    03/11/2019

So using the table above as an example what I'm trying to do with a similar table is extract a specific Type from each Distinct ID. 因此,以上面的表格为例,我要对类似表格进行的操作是从每个唯一ID中提取特定的Type。 So let's say I only want to Select Type B from each Distinct ID. 假设我只想从每个唯一ID中选择类型B。 Now, the big confusion starts for me when I incorporate the Date. 现在,当我合并Date时,对我来说就大为混乱。 I want to Select Type B from each ID but only if Type B is the most recent date. 我想从每个ID中选择类型B,但前提是类型B是最近的日期。

So in this instance the only row with Type B as the last date would be the last row. 因此,在这种情况下,类型B作为最后日期的唯一行将是最后一行。
3 B 03/11/2019

Any suggestions as to what my query should look like? 关于查询的外观有什么建议吗?

With NOT EXISTS: 有不存在:

select t.* from tablename t
where t.type = 'B'
and not exists (
  select 1 from tablename
  where id = t.id and date > t.date
)

See the demo . 参见演示
Results: 结果:

| ID  | TYPE | DATE                |
| --- | ---- | ------------------- |
| 3   | B    | 2019-03-11 00:00:00 |

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

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