1

以下に示す例のようなテーブルがあります。

AccountNo  DateOfOrder    OrderID   
-----------------------------------------   
 123       March 1 2010   1   
 222       March 3 2010   2   
 123       April 1 2010   3   
 345       March 15 2010  77   
 123       june 1 2010    55   
 123       march 5 2010   33   
 345       march 1 2010   99   
 222       june 1 2010    7   
 222       june 2 2010    22   

3つの列を出力するクエリが必要です。

AccountNo、、MostRecentDateOfOrder_SecondMostRecentDateOfOrder

4

2 に答える 2

2

SQL Serverのバージョンを指定しませんでしたが、PIVOTSQLServer2005以降でCTEとこれを使用できます。

;with cte as
(
  select accountno, dateoforder, orderid,
    row_number() over(partition by accountno 
                      order by dateoforder desc) rn
  from yourtable
)
select accountno,
  [1] MostRecentOrder,
  [2] SecondMostRecent
from 
(
  select accountno, dateoforder, rn
  from cte
) x
pivot 
(
  max(dateoforder)
  for rn in ([1], [2])
) p

SQL FiddlewithDemoを参照してください

于 2012-08-30T14:48:28.847 に答える
0

これは私がOracleでそれを行う方法です:-

SELECT MAX(ACCOUNTNO), 
       MAX(DateOfOrder) AS SecondMostRecentDateOfOder,
       MIN(DateOfOrder) AS MostRecentDateOfOrder 
FROM (
SELECT ACCOUNTNO, DateOfOrder, RANK() OVER (order by ACCOUNTNO, DateOfOrderdesc) RANK
FROM TABLE
)
WHERE RANK < 3;
于 2012-08-30T15:08:28.893 に答える