2010-09-22 90 views
1

我有一張名爲取款的表格,其中包含:名稱,年份,期間,金額。獲取記錄的最大值

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. 

回答

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) 
+0

看起來非常接近,但你忘記了這個時期.. – 2010-09-22 13:06:27

+0

謝謝,但那個時期呢?如果有值3和4,它應該選擇4.我如何取最大年份的最長時間? – mohs 2010-09-22 15:37:16

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) 
+0

用你需要的列名替換'*' – Kashif 2010-09-22 13:09:11

+0

感謝您的幫助,但那段時間呢?如果有兩個時期3,4,它應該是最大時期,那麼我應該包括什麼? – mohs 2010-09-22 15:36:16

+0

Quassnoi的解決方案應該爲你工作。不是嗎? – Kashif 2010-09-22 15:53:00

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

當使用聚合函數(即最小,最大,count)非聚合列應列在「集團「條款。在這種情況下,「名稱」。

+0

不,這是行不通的,因爲每年都會有不同的時間段,我應該在每個名稱的最大年份中使用最長時間 – mohs 2010-09-22 15:55:24

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 
+0

我會嘗試這種做法並恢復原狀。我希望它會在每個名稱的最大年份中獲得最大年份和最大期限。謝謝,並會回來 – mohs 2010-09-22 15:58:05

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(Year),max(Period)的問題是「2010 1」晚於「2009 4」,而max(Year),max(Period)將返回「2010 4」這不存在。 「年* 100 +期」爲您提供了一個良好的分類。