我在下面的SQL中获得了此表,我需要返回“如果汽车购买者是一个理性的人,将永远不会使用的汽车销售商”或“所有汽车价格都比其他汽车价格昂贵的销售商” 。我试图做一个自己加入的想法,但是我无法使其工作。最终的输出应该是供应商3,因为其汽车3和4的价格比其他选择贵。
id car_vendor_id vendor_name car_id price
---------------------------------------------
1 1 Vendor 1 1 25000
2 1 Vendor 1 2 40000
3 2 Vendor 2 2 35000
4 2 Vendor 2 3 25000
5 3 Vendor 3 3 28000
6 3 Vendor 3 4 40000
7 4 Vendor 4 4 35000
8 4 Vendor 4 5 20000
9 5 Vendor 5 5 18000
10 5 Vendor 5 6 32000
11 6 Vendor 6 6 30000
12 6 Vendor 6 7 20000
答案 0 :(得分:1)
一种方法是row_number()
和聚合:
select car_vendor_id, vendor_name
from (select t.*,
rank() over (partition by car_id order by price) as seqnum
from t
) t
group by car_vendor_id, vendor_name
having min(seqnum) > 1;
having
子句选择的行中,卖方没有根据价格将车辆“排在首位”。
答案 1 :(得分:0)
以下查询使用CTE来计算每辆车的价格顺序,因此最昂贵的是1。
然后它排除了行,其中有行不是最昂贵的供应商,最后检查它们不是唯一的汽车销售商。
declare @Car table(Vendor int, Car int, Price int)
insert @Car values (1,1,25000),(1,2,40000),(2,2,35000),(2,3,25000),(3,3,28000),(3,4,40000),(4,4,35000),(4,5,20000),(5,5,18000),(5,6,32000),(6,6,30000),(6,7,20000)
;with Price as (
select *, row_number() over(partition by Car order by Price desc) as r from @Car Car
)
select * from Price
where not exists(select * from Price p2 where p2.Vendor=Price.Vendor and p2.r>1)
and Vendor not in (
select Vendor from @Car where Car in (select Car from @Car group by Car having count(*)=1)
)
答案 2 :(得分:0)
检查下一个查询:
declare @car table(Vendor int, Car int, Price int);
insert @car
values
(1,1,25000),(1,2,40000),(2,2,35000),(2,3,25000),
(3,3,28000),(3,4,40000),(4,4,35000),(4,5,20000),
(5,5,18000),(5,6,32000),(6,6,30000),(6,7,20000);
with
a as (
select
vendor, price,
count(*) over(partition by car) cq,
count(*) over(partition by vendor) vcq,
max(price) over(partition by car) xcp
from @car
)
select vendor
from a
where cq > 1 and xcp = price
group by vendor, vcq
having count(*) = vcq;
要在线尝试查询,请单击here。