[在SQL Server中使用CASE语句的最小MAX

问题描述 投票:-1回答:3

enter image description here

我有这样一张桌子。我要输入的所有国家名称,人口编号,以及如果MAX中的人口,则标记MAX,并类似地标记MIN。我已经在下面使用CASE语句在SQL Server中编写了查询。

/* MIN/MAX Population amongst the countries */
SELECT 
    country, population,
    CASE
        WHEN population == MIN(population) THEN "MIN"
        WHEN population == MAX(population) THEN "MAX" ELSE "NA"
    END as "pop_stats"
FROM
    countries_by_population;
sql sql-server case-statement
3个回答
1
投票

Demo on db<>fiddle

首先,应该通过如下所示存储@Min_Population@Max_Population

DECLARE @Min_Population decimal(18,2), @Max_Population decimal(18,2)
SELECT @Min_Population = MIN(population), @Max_Population = MAX(population)
FROM countries_by_population

[之后,您可以像这样比较每个项目的值(请注意,SQL中的字符用单引号而不是双引号封闭)

CASE
    WHEN population = @Min_Population THEN 'MIN'
    WHEN population = @Max_Population THEN 'MAX' ELSE 'NA'
END as pop_stats

完整查询

DECLARE @Min_Population decimal(18,2), @Max_Population decimal(18,2)
SELECT @Min_Population = MIN(population), @Max_Population = MAX(population)
FROM countries_by_population

SELECT country, population,
    CASE
        WHEN population = @Min_Population THEN 'MIN'
        WHEN population = @Max_Population THEN 'MAX' ELSE 'NA'
    END as pop_stats
FROM countries_by_population;

0
投票

您可以使用窗口分析函数,例如DENSE_RANK()ORDER BY population(默认)顺序中包含descending子句的ascending来通过从MIN返回值来确定MAX1值以便分别在CASE语句中使用(DENSE_RANK()函数返回极值中ties发生情况下满足相关条件的一行以上]]

SELECT country, population,
       CASE
         WHEN DENSE_RANK() OVER ( ORDER BY population ) = 1 THEN 'MIN'
         WHEN DENSE_RANK() OVER ( ORDER BY population DESC ) = 1 THEN 'MAX' ELSE 'NA'
       END AS "pop_stats"
  FROM countries_by_population
 ORDER BY population DESC

顺便说一句,不要对导出的列值使用双引号,而应使用单引号。

Demo


-1
投票

使用over()使其成为没有分区的窗口函数:

© www.soinside.com 2019 - 2024. All rights reserved.