这是我的示例数据:
declare @cities table
(
city varchar(100),
toyota int,
honda int,
hyundai int,
ford int,
chevy int
)
insert into @cities
select 'miami', 23, 65, 30, 65,12 union
select 'san francisco', 12, 7,3, 7,12 union
select 'houston', 6,3, null, 5, 4
我可以使用简单的where
语句找到每行的最大值,如下所示:
select count(*) from @cities where toyota > honda and toyora > hyundai...
但是,假设我想要最大值,但也看看是否有其他人拥有该最大值。在另一方面,我试图找到谁并列第一名。
因此,理想的结果将是 miami 和旧金山,因为两个城市都是最高价值的(即 honda 和 ford 在 miami 中排名第一, toyota 和 chevy 并列于第一名 >旧金山)。
答案 0 :(得分:2)
使用UNPIVOT
和DENSE_RANK
。
<强> SQL DEMO 强>
WITH cte as (
SELECT city, brand, qty
FROM (SELECT city, toyota, honda, hyundai, ford, chevy
FROM @cities) p
UNPIVOT ( qty FOR brand IN (toyota, honda, hyundai, ford, chevy)
) as unpvt
), top_brands as (
SELECT *, dense_rank() over (partition by city order by qty desc ) as rnk
FROM cte
)
SELECT city
FROM top_brands
GROUP BY city
HAVING COUNT(case when rnk = 1 then 1 end) > 1
输出