简体   繁体   English

计算日期之间的分钟数并获得前10名

[英]calculate minutes between dates and get top 10

So I have a table that holds two different dates and I am selecting the minutes difference between: 因此,我有一个表格,其中包含两个不同的日期,并且我选择以下两者之间的分钟差:

    select customerID, customers.telNumber,
   sum(round((enddate - startdate) * 1440)) over (partition by telNumber) total_mins
    from table;

And after that I want to get only the top 5 that have the highest amount of minutes, something like 然后,我只想获取分钟数最多的前5名,例如

     rank() over (partition by total_mins order by total_mins)

How would one go about doing that? 人们将如何去做呢?

Something like this should work for you: 这样的事情应该为您工作:

SELECT * 
FROM (
  SELECT customerId, telNumber, rank() over (order by total_mins) rnk
  FROM (
    SELECT customerId,telNumber,
     sum(round((enddate - startdate) * 1440)) over (partition by telNumber) total_mins
    FROM YourTable
  ) t
) t
WHERE rnk <= 10

This will get you ties, so it could return more than 10 rows. 这将使您联系起来,因此它可能返回10行以上。 If you only want to return 10 rows, use ROW_NUMBER() instead of RANK() . 如果只想返回10行,请使用ROW_NUMBER()而不是RANK()

SQL Fiddle Demo SQL小提琴演示

I would add to sgeddes's example that the combination of rank() and row_number() is the best as rank() may return the same rank values for all or few rows. 我将在sgeddes的示例中添加一下,rank()和row_number()的组合是最好的,因为rank()可能会为所有或几行返回相同的等级值。 But row_number() will always be different. 但是row_number()总是不同的。 I'd use row_number() in Where clause, not rank(). 我会在Where子句中使用row_number(),而不是rank()。

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

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