Sybase

返回列的最大值

  • January 6, 2012

桌子:

SubSection | TradingId  | Year  | Amount
100A           5001       2004  -120
200B           5001       2005  -130
300C           5002       2006  -140
300C           5003       2007  -150

我想根據小節返回 MAX 交易 ID,我想要這個:

SubSection | TradingId  | Year  | Amount
100A           5001       2004  -120
200B           5001       2005  -130
300C           5003       2007  -150

我嘗試使用 GROUPBY 小節選擇 MAX,嘗試 HAVING MAX 等但沒有運氣

SELECT t1.*
FROM the_table t1
WHERE t1.trading_id = (SELECT max(t2.trading_id)
                   FROM the_table t2
                   WHERE t2.subsection = t1.subsection)

這將返回表中的所有列,但對於每個子部分的最大交易 ID:

Select t2.*
from (
  Select max(TradingId) as MaxTradingId, SubSection
  from TableT
  group by SubSection
) t1 join TableT t2 on t1.MaxTradingId = t2.TradingId and t1.SubSection = t2.SubSection

請試一試。

引用自:https://dba.stackexchange.com/questions/10259