1

我是 SQL Server 的新手。我正在尝试将我的 Access 数据库转换为 SQL Server。这是我的问题,我在这里有一张桌子。

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 获得相同的结果。

我希望有人能帮帮忙。谢谢。

4

3 回答 3

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
于 2013-06-06T04:08:35.033 回答
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演示

于 2013-06-06T03:30:01.927 回答
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

不过,我并没有完全得到您要求的结果,您的选择不应该每辆车只返回一行吗?

于 2013-06-06T03:31:14.927 回答