SQL查询 - 由多个列组成,但不同

时间:2010-03-28 19:45:38

标签: sql sql-server greatest-n-per-group

我有一个出价表,如下:

SellID INT FOREIGN KEY REFERENCES SellItem(SellID),
CusID INT FOREIGN KEY REFERENCES Customer(CusID),
Amount FLOAT NOT NULL,
BidTime DATETIME DEFAULT getdate()

现在在我的网站上,我需要向用户显示当前的出价;只有最高出价,但没有重复相同的用户。

  SELECT CusID, 
         Max(Amount) 
    FROM Bid 
   WHERE SellID = 10 
GROUP BY CusID 
ORDER BY Max(Amount) DESC

这是迄今为止我取得的最好成绩。这为每个用户的CusID提供了最高出价,并按升序排序。但我也需要为每个结果获得BidTime。当我尝试将BidTime放入查询时:

  SELECT CusID, 
         Max(Amount), 
         BidTime 
    FROM Bid 
   WHERE SellID = 10 
GROUP BY CusID 
ORDER BY Max(Amount) DESC 

我被告知“Column'Bid.BidTime'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。”

因此我尝试了:

  SELECT CusID, Max(Amount), BidTime 
    FROM Bid 
   WHERE SellID = 10 
GROUP BY CusID, BidTime 
ORDER BY Max(Amount) DESC

但这会返回所有行。没有区别。有关解决这个问题的任何建议吗?

4 个答案:

答案 0 :(得分:2)

使用:

  SELECT b.cusid,
         b.amount,
         b.bidtime
    FROM BID b
    JOIN (SELECT t.cusid,
                 t.sellid,
                 MAX(t.amount) AS max_amount
            FROM BID t
           WHERE t.sellid = 10
        GROUP BY t.cusid, t.sellid) x ON x.max_amount = b.amount
                                     AND x.cusid = b.cusid
                                     AND x.sellid = b.sellid
ORDER BY b.amount DESC

使用聚合意味着您无法在同一查询中获取该给定值的信息。您必须将表的副本与聚合数据(连接是典型选择)相关联才能获取相关信息。

答案 1 :(得分:1)

一种方式,假设另一种思考方式是返回每个用户的最新出价:

SELECT b.cusID, b2.LatestBidTime, b.Amount 
FROM Bid b
    JOIN (
        SELECT cusID, MAX(BidTime) AS LatestBidTime
        FROM Bid
        WHERE SellID = 10
        GROUP BY cusID) b2 ON b.cusID = b2.cusID AND b.BidTime = b2.LatestBidTime
WHERE b.SellID = 10

答案 2 :(得分:1)

select b.*
from Bid b
inner join (
    SELECT CusID, Max(Amount) as MaxBid
    FROM Bid 
    WHERE SellID=10 
    GROUP BY CusID 
) bm on b.CusID = bm.CusID and b.Amount = bm.MaxBid
where b.SellID = 10
ORDER BY b.Amount DESC 

答案 3 :(得分:0)

据推测,最近出价最高,对吧?所以只需将MAX放在BidTime上。

SELECT CusID, Max(Amount), MAX(BidTime)
FROM Bid 
WHERE SellID=10 
GROUP BY CusID ORDER BY Max(Amount) DESC