3

假设,我有一个名为 items 的表:

sender_id receiver_id goods_id price
  2            1          a1   1000
  3            1          b2   2000
  2            1          c1   5000
  4            1          d1   700
  2            1          b1   500   

在这里,我想从items表中按价格降序选择 sender_id,goods_id,这样不会出现多次包含相同 sender_id 值的行(此处为 sender_id 2)。我使用了以下查询,但徒劳无功:

select distinct sender_id,goods_id from items where receiver_id=1 order by price desc

结果显示所有五个元组(记录),其中包含 sender_id 2 的元组按时间降序排列三次。但我想要的是只显示三个记录,其中一个的 sender_id 为 2,最高价格为 5000。应该我愿意?我的预期输出是:

sender_id goods_id
   2         c1
   3         b2
   4         d1
4

4 回答 4

2

获取每个组的最高价格,您可以执行以下操作:

SELECT T1.*
FROM (
    SELECT
     MAX(price) AS max_price,
     sender_id
    FROM items
    GROUP BY sender_id
) AS T2
INNER JOIN items T1 ON T1.sender_id = T2.sender_id AND T1.price = T2.max_price
WHERE T1.receiver_id=1 
ORDER BY T1.price
于 2014-01-09T04:46:22.263 回答
1

试试这个:

SELECT i.sender_id, i.goods_id 
FROM items i 
INNER JOIN (SELECT i.sender_id, MAX(i.price) AS maxPrice
            FROM items i WHERE i.receiver_id=1 
            GROUP BY i.sender_id
           ) AS A ON i.sender_id = A.sender_id AND i.price = A.maxPrice
WHERE i.receiver_id=1

或者

SELECT i.sender_id, i.goods_id 
FROM (SELECT i.sender_id, i.goods_id 
      FROM (SELECT i.sender_id, i.goods_id 
            FROM items i WHERE i.receiver_id=1 
            ORDER BY i.sender_id, i.price DESC
           ) AS i 
      GROUP BY i.sender_id
     ) AS i
于 2014-01-09T05:11:01.640 回答
0
select distinct (sender_id,goods_id) from items where receiver_id=1 order by price desc;

你可以这样使用。

于 2014-01-09T05:09:19.443 回答
0

请试试这个

select sender_id,goods_id from items t1
where not exists (select 1 from items t2
                  where t2.sender_id = t1.sender_id
                    and t2.receiver_id = t1.receiver_id
                    and t2.price > t1.price)
 and receiver_id = 1
order by price desc
于 2014-01-09T05:18:50.957 回答