找到每行最高价值的关系?

时间:2018-03-13 16:26:17

标签: sql-server-2008 tsql

这是我的示例数据:

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 并列于第一名 >旧金山)。

1 个答案:

答案 0 :(得分:2)

使用UNPIVOTDENSE_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

输出

enter image description here