简体   繁体   English

如何 SELECT DISTINCT 一列并按另一列排序?

[英]How to SELECT DISTINCT one column and ORDER by another column?

I have a table like this我有一张这样的桌子

++++++++++++++++++++++++++++++++++++++++++++++++++++++++
id |  domain  | domain_date           | domain_status  |
1  |abc_com   | 2022-08-20 15:42:35   |       1        |
2  |def_com   | 2022-08-20 15:44:31   |       1        |
3  |def_com   | 2022-08-20 15:40:05   |       1        |
4  |abc_com   | 2022-08-20 15:35:05   |       0        |
5  |ghi_com   | 2022-08-20 15:25:05   |       1        |
6  |ghi_com   | 2022-08-20 15:25:00   |       1        |
7  |abc_com   | 2022-08-19 15:22:00   |       1        |
8  |ghi_com   | 2022-08-20 15:25:05   |       1        |
9  |abc_com   | 2022-08-20 15:21:00   |       1        |
10 |abc_com   | 2022-08-19 15:21:20   |       1        |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++

I want to get latest entries of five records from the table but I don't want duplicate domains.我想从表中获取五个记录的最新条目,但我不想要重复的域。 I tried with SELECT DISTINCT, Distinct works fine if I select only domain it cuts the duplicates but if selects two columns我尝试使用 SELECT DISTINCT,如果我仅使用 select 域,则 Distinct 可以正常工作,它会减少重复项,但如果选择两列

SELECT DISTINCT domain, domain_date FROM Domains

It still shows duplicates because the dates are different它仍然显示重复,因为日期不同

What is the workaround for this?解决方法是什么?

if you group on max domain date, you will get a distinct list of domains with their max domain_date:如果您按最大域日期分组,您将获得一个不同的域列表及其最大域日期:

select 
    domain, max(domain_date) as MaxOfDomainDate
from table
group by domain

We can join the table on this result set if we want to get the status that goes with the domain record for that date:如果我们想获得与该日期的域记录一起出现的状态,我们可以加入这个结果集的表:

select A.domain, A.domain_date, A.domain_status
from
table A
inner join
(
    select 
        domain, max(domain_date) as MaxOfDomainDate
    from table
    group by domain
) B
on A.domain = B.domain
and A.domain_date = B.domain_date;

You should be able to add ordering and TOP or LIMIT to such a query pretty easily to get the "latest 5" and so on (I'll leave that as an exercise to the reader;) )您应该能够很容易地向这样的查询添加排序和 TOP 或 LIMIT 以获得“最新的 5”等等(我将把它作为练习留给读者;))

You may need to create a Join table in which you set both condition for column domain and domain_date.您可能需要创建一个联接表,在其中设置列域和域日期的条件。

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

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