我正在尝试获取特定商品的最高出价,并显示出价该金额的用户
我能够通过两个不同的查询获得结果,每个查询返回我想要的子集
select username, auctionbids.itemid, description, bidamt from AuctionBids
inner join users on auctionbids.userid = users.id
inner join auctionitems on auctionbids.itemid = auctionitems.itemid
select ab.itemid,max(ab.bidamt) as bidmax from auctionbids as ab group by ab.itemid
我想获取用户名,itemid,item描述符,max(bidamt)连接到三个表-用户,拍卖品,拍卖出价。
用户包含用户名和用户名
拍卖项目包含项目ID和项目说明
拍卖标书包含用户ID,物品ID,比阿姆特
答案 0 :(得分:1)
以下查询应执行您想要的操作:
SELECT a.item_description,a.username,a.bidamt FROM
(
SELECT au.item_description,u.username,ab.bidamt, RANK() OVER(PARTITION BY au.itemid ORDER BY ISNULL(ab.bidamt,0) DESC) AS [Rank]
FROM auctionitems au
LEFT JOIN auctionbids ab ON au.itemid = ab.itemid
LEFT JOIN users u ON ab.userid = u.userid ) a WHERE [Rank] = 1
答案 1 :(得分:1)
正如您所说,两个不同的查询每个都返回您想要的子集,您的查询应该像这样:
SELECT am.username, am.itemid, am.descripton, max(am.bidamt) AS bidmax
FROM (
SELECT username, auctionbids.itemid, auctionitems.description, bidamt FROM AuctionBids
INNER JOIN users ON auctionbids.userid = users.id
INNER JOIN auctionitems ON auctionbids.itemid = auctionitems.itemid
) AS am
GROUP BY am.itemid
答案 2 :(得分:0)
没有示例数据,就无法验证其是否正常工作。但是您需要将bidamt
与MAX
bidamt
与特定项目进行匹配。
SELECT DISTINCT
users.username,
auctionbids.itemid,
auctionitems.description,
auctionbids.bidamt
FROM
users
INNER JOIN auctionbids on users.userid = auctionbids.userid
INNER JOIN auctionitems on auctionbids.itemid = auctionitems.itemid
WHERE
auctionbids.bidamt = (SELECT MAX(bidamt) OVER (PARTITION BY itemid, description))
AND
itemid = < whatever you want >
答案 3 :(得分:0)
感谢导致此查询的想法-
SELECT am.*, auctionbids.submitted, users.username, auctionitems.description
FROM
(SELECT ab.itemid, max(ab.bidamt) as bidmax
FROM
auctionbids ab
GROUP BY ab.itemid) AS am
INNER JOIN auctionbids ON am.itemid = auctionbids.itemid and am.bidmax = auctionbids.bidamt
INNER JOIN users ON auctionbids.userid = users.id
INNER JOIN auctionitems ON auctionbids.itemid = auctionitems.itemid
因此,基本上,必须在itemid上通过group by找到最大值,然后与其余表进行内部联接以获取属性。