我有一张桌子:
login_id product_name price bid_price
123 onion 500 515
150 onion 500 517
115 tomato 475 580
120 potato 399 410
145 potato 399 413
145 potato 399 405
我需要选择那些记录,其product_name具有多个出价,而不是每个产品的最高出价
预期结果:
login_id product_name price bid_price
123 onion 500 515
120 potato 399 410
145 potato 399 405
答案 0 :(得分:3)
通过使用row_number()
with cte as
(
select *, row_number() over(partition by porduct_name order by bid_price desc) rn
from t1
) select * from cte where rn<>1
login_id porduct_name price bid_price
123 onion 500 515
120 potato 399 410
145 potato 399 405
答案 1 :(得分:2)
您可以使用相关子查询
select * from tablename a
where not exists
(select 1 from tablename b where a.product_name=b.product_name
group by b.product_name having count(bid_price)=1)
and bid_price not in
(select max(bid_price) from tablename c where a.product_name=c.product_name)
输出:
login_id porduct_name price bid_price
123 onion 500 515
120 potato 399 410
145 potato 399 405
答案 2 :(得分:1)
您可以加入每种产品的最高出价,然后选择其他所有内容
select t.*
from your_table t
left join
(
select product_name, max(bid_price) as maxbid
from your_table
group by product_name
) tmp on tmp.product_name = t.product_name
and tmp.maxbid = t.bid_price
where tmp.product_name is null
答案 3 :(得分:0)
您可以使用Common Table Expression
with cte_test1
as
(
select t.product_name, count(*) [RowsCount],max(t.bid_price) [max_bid_price]
from dbo.Test001 t
group by t.product_name
)
select *
from dbo.Test001 t
join cte_test1 c on c.product_name=t.product_name
where c.RowsCount>1 and t.bid_price<c.max_bid_price