2013-06-06 102 views
1

我是SQL Server新手。我試圖將我的Access數據庫轉換爲SQL Server。 這裏是我的問題,我在這裏得到一個表。SQL Server 2005獲取列的最後一條記錄

CarID CustomerName  Date Replied   StatusID Offer 
    1   Karl   05-01-2013    1  $1000 
    1   Karl   05-02-2013    1  $1000 
    1   Kathy   05-03-2013    1  $1500 
    1   Karl   05-04-2013    2  $1000 
    2   Karl   05-04-2013    1  $2000 

我想作爲

CarID CustomerName  Date Replied   StatusID Offer 
    1   Kathy   05-03-2013    1  $1500 
    1   Karl   05-04-2013    2  $1000 
    2   Karl   05-04-2013    1  $2000 

,以顯示我的數據在MS Access

I used SELECT CarID, Last(CustomerName) as CustomerName, Max(Date) as Date Replied, Last(StatusID) as StatusID, Last(Offer) as Offer from viewCarOffers GROUP BY CarID

問題與SQL Server。它沒有最後的功​​能。我不知道如何使用SQL Server獲得相同的結果。

我希望有人能幫忙。謝謝。

+0

我使用該記錄的視圖。它實際上是一個嵌套/關係表。 (tblCars,tblMake,tblCarOffers,tblModel等) – user2180795

+0

看起來,Last()函數返回表中的最後一條記錄(在快速谷歌搜索之後,這是我發現的,我不熟悉ms訪問我)。除非你知道他們插入的順序,否則我不確定你是否可以複製它。如果你有一個插入時間戳或一個標識來知道插入順序,你可以使用一個子查詢,比如'(從viewCarOffers_vco中選擇top 1 vco.customername,其中vco.carId = viewCarOffers.customerName order by {identity或timestamp} desc)'in該查詢代替'Last(CustomerName)'。重複你的其他價值觀。 – liebs19

回答

0

嘗試

SELECT o.CarID, 
     o.CustomerName, 
     o.Date 'Date Replied', 
     o.StatusID, 
     o.Offer 
    FROM 
(
SELECT CarID, CustomerName, MAX(Date) Date 
    FROM viewCarOffers 
GROUP BY CarID, CustomerName 
) q JOIN viewCarOffers o 
    ON o.CarID = q.CarID 
    AND o.CustomerName = q.CustomerName 
    AND q.Date = o.Date 
ORDER BY CarID, CustomerName 

輸出:

| CARID | CUSTOMERNAME |    DATE REPLIED | STATUSID | OFFER | 
------------------------------------------------------------------------ 
|  1 |   Karl | May, 04 2013 00:00:00+0000 |  2 | $1000 | 
|  1 |  Kathy | May, 03 2013 00:00:00+0000 |  1 | $1500 | 
|  2 |   Karl | May, 04 2013 00:00:00+0000 |  1 | $2000 | 

這裏是SQLFiddle演示

+0

非常感謝你!它解決了我的問題。 :d – user2180795

0

在SQL Server中,你可以做一個自我加入到選擇最大的日期。

SELECT co.CarID, 
    Last.CustomerName AS CustomerName, 
    Last.Date AS [DATE Replied], 
    Last.StatusID AS StatusID, 
    Last.Offer AS Offer 
FROM viewCarOffers co 
    INNER JOIN 
    (
     SELECT ROW_NUMBER() OVER (PARTITION BY carid ORDER BY DATE DESC) ROW, 
      CarId, 
      CustomerName, 
      DATE, 
      StatusId, 
      Offer 
     FROM viewCarOffers co2 
    ) LAST ON co.carid = last.carid AND last.row = 1 
GROUP BY co.CarId, Last.CustomerName, Last.Date, Last.StatusId, Last.Offer 

雖然我不太滿意你要求的結果,但是不應該只選擇每輛車返回一行?

2

試試這個

SELECT 
    CarId, 
    CustomerName, 
    DATE, 
    StatusId, 
    Offer 
FROM 
(
    SELECT 
    ROW_NUMBER() OVER (PARTITION BY carid, CustomerName ORDER BY DATE DESC) ROW, * 
    FROM viewCarOffers 
) vco 
WHERE ROW = 1 
ORDER BY CarId, offer DESC 
相關問題