获取记录的最大值

时间:2010-09-22 12:58:01

标签: sql

我有一个名为Withdrawals的表格,其中包括:姓名,年份,期限,金额。

EX:

Name   Year    Period    Amount
--------------------------------
Jim    2010    1         100
Jim    2009    4         99
Jim    2009    3         17
Kim    2007    2         234
Ryu    2008    5         555

我被困住了,因为我无法获得该名称的最新价值。最近一年的最近一段时间。

我尝试使用查询:

select max(year), max(period), name from withdrawarls

但我得错了结果。

那么,我怎样才能得到正确的值:

Jim, 2010, 1, 100
Kim, 2007, 2, 234
RYU, 2008, 5, 555.

5 个答案:

答案 0 :(得分:2)

MySQLPostgreSQL

SELECT  t.*
FROM    (
        SELECT  DISTINCT name
        FROM    mytable
        ) td
JOIN    mytable t
ON      (t.year, t.period) =
        (
        SELECT  year, period
        FROM    mytable ti
        WHERE   ti.name = td.name
        ORDER BY
                name DESC, year DESC, period DESC
        LIMIT 1
        )

SQL Server

SELECT  t.*
FROM    (
        SELECT  DISTINCT name
        FROM    mytable
        ) td
CROSS APPLY
        (
        SELECT  TOP 1 *
        FROM    mytable ti
        WHERE   ti.name = td.name
        ORDER BY
                year DESC, period DESC
        ) t

SQL ServerOracle

SELECT  *
FROM    (
        SELECT  t.*, ROW_NUMBER() OVER (PARTITION BY name ORDER BY year DESC, period DESC) AS rn
        FROM    mytable
        ) t
WHERE   rn = 1

答案 1 :(得分:0)

SELECT * 
FROM Withdrawals w
JOIN (Select Name, Max(year) year
      FROM Withdrawals
      group by name) t ON (t.Name = w.Name AND t.Year = w.Year)

答案 2 :(得分:0)

select *  from @tbl t
where t.year in (select max(year) from @tbl group by name)

使用您提供的数据

declare @tbl table
(
    name varchar(10),
    year varchar(10),
    period int,
    amount int
)

insert into @tbl  select 'Jim', '2010', 1, 100
insert into @tbl select 'Jim', '2009', 4, 99
insert into @tbl select 'Jim', '2009', 3, 17
insert into @tbl select 'Kim', '2007', 2, 234
insert into @tbl select  'RYU', '2008', 5, 555

select *  from @tbl t
where t.year in (select max(year) from @tbl group by name)

答案 3 :(得分:0)

select max(year), max(period), name from withdrawals group by name;

使用聚合函数(即min,max,count)时,非聚合列应列在“group by”子句中。在这种情况下,“名称”。

答案 4 :(得分:0)

我们希望期间小于100:

SELECT w.Name, w.Year, w.Period, w.Value
FROM Withdrawals w,
(SELECT Name, MAX(Year * 100 + Period) as maxTime
 FROM Withdrawals
 GROUP BY Name) AS maxW
WHERE w.Name = maxW.Name
AND w.Year * 100 + w.Period = maxW.maxTime

max(年),最大(期间)的问题是“2010 1”晚于“2009 4”,而max(年),最大(期间)将返回“2010 4”,这不存在。 “年* 100 +期间”为您提供了良好的分类。