简体   繁体   English

从sql中的2列中仅选择不同的值

[英]Selecting only distinct values from 2 columns in sql

I have a Table in my database. 我的数据库中有一个表。 I need only 2 columns from that entire database. 我只需要整个数据库中的2列。 Also, I need the distinct values from the two columns. 另外,我需要这两列中的不同值。 The data is as follows: 数据如下:

ID          DATE
00432CDE    1/4/2016
64031QCL    1/4/2016
64031QCL    1/5/2016
64031QCL    1/6/2016
817176AA    1/4/2016
817176AA    1/5/2016
55818FAN    1/4/2016
55818FAN    1/5/2016
92912QAA    1/4/2016
92912QAA    1/5/2016
532621AA    1/4/2016
532621AA    1/5/2016
05344AAN    1/4/2016
05344AAN    1/5/2016
17305EFN    1/4/2016

As you can see there are multiple date values and because of that IDs are duplicated. 如您所见,存在多个日期值,因此ID重复。 I want to write a code where I can get the last date along with the ID. 我想编写一个代码,在其中可以获取最后的日期以及ID。 So the columns should look like this: 因此,列应如下所示:

ID          DATE
00432CDE    1/4/2016
64031QCL    1/6/2016
817176AA    1/5/2016
55818FAN    1/5/2016
92912QAA    1/5/2016
532621AA    1/5/2016
05344AAN    1/5/2016
17305EFN    1/4/2016

Thank you! 谢谢!

Use an aggregate on your DATE column to choose which one to display. 使用DATE列上的汇总来选择要显示的汇总。 You want MAX() : 您想要MAX()

SELECT ID, MAX(DATE)
FROM yourTable
GROUP BY ID

Note: Grouping by all non-aggregated columns achieves the same result as DISTINCT , so you won't need the DISTINCT keyword. 注意:按所有未聚合的列进行分组可获得与DISTINCT相同的结果,因此您不需要DISTINCT关键字。

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

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