用于选择最新重复项的SQL查询

时间:2014-07-24 06:42:21

标签: sql

我有一个值表,每个条目都存有一个日期,例如

  • 名称
  • 年龄
  • PaymentAmount
  • 日期

有人可以帮我写一个查询,只显示某个年龄段内任何人的最近一次付款。

例如,如果我有5个条目,并希望最近支付所有20-25岁的人

Allan, 45, $1500, 1/1/2014
Tim, 22, $1500, 1/2/2001
John, 25, $2000, 2/3/2001
Tim, 22, $2500, 1/2/2010
John, 25, $3000, 2/3/2010

它只返回底部的2行

5 个答案:

答案 0 :(得分:1)

最简单的方法,请尝试以下查询
  select name,age,paymentamount,date from yourtablename where date in (select max(date) from yourtablename where age between 20 and 25 and group by name);

答案 1 :(得分:1)

此查询会为您提供20岁和25岁最近一次付款的所有记录。根据您的数据库语法使用TOP 2LIMIT 2rownum <=2来限制

SELECT NAME,AGE,PAYMENTAMOUNT,DATE FROM MY_TABLE
WHERE AGE BETWEEN 20 AND 25 
AND DATE IN 
    (
        SELECT MAX(DATE) 
    FROM MY_TABLE 
    WHERE 
    AGE BETWEEN 20 AND 25
     );

根据horse_with_no_name编辑:

SELECT NAME,AGE,PAYMENTAMOUNT,DATE 
FROM the_table
WHERE AGE BETWEEN 20 AND 25 
AND DATE IN 
    (
        SELECT (DATE) 
    FROM the_table
    WHERE 
    AGE BETWEEN 20 AND 25 order by date desc limit 2
     )
limit 2;

小提琴参考:http://sqlfiddle.com/#!15/17e37/10

答案 2 :(得分:0)

您可以在

之间使用
select * from meta where title='$title' and (date between '$start_date' and '$end_date').

答案 3 :(得分:0)

您应该创建一个带有标识列的表,以使您的生活更轻松

  • ColumnPrimaryKey IDENTITY(1,1)
  • 名称
  • 年龄
  • PaymentAmount
  • 日期

SELECT TOP 2 * FROM [TableName] Where Age BETWEEN 20 AND 25 ORDER BY [PrimaryKey] DESC

上述查询将返回表格中插入的前两行

答案 4 :(得分:0)

您没有说明您的DBMS,因此这是ANSI SQL

select *
from (
  select name, 
         age,
         PaymentAmount,
         Date, 
         row_number() over (partition by name order by date desc) as rn
  from the_table
  where age between 22 and 25
) t
where rn = 1;

另一种选择是使用共同相关的子查询:

select name,age,paymentamount,date 
from the_table t1
where age between 22 and 25 
and date = (select max(date) 
            from the_table t2
             where t2.name = t1.name
               and t2.age between 22 and 25)
order by name;

通常,具有窗口函数的解决方案比共同相关的子查询更快,因为只需要对表进行一次访问。

SQLFiddle:http://sqlfiddle.com/#!15/17e37/4

顺便说一下:有一个名为age的列有点可疑,因为你需要每年更新一次。您应该存储出生日期,然后计算检索数据时的年龄。