在MSSQL中使用CASE语句的最小MAX

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

enter image description here

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

/* 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-server case-statement
2个回答
0
投票

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

SELECT country, population,
    CASE
        WHEN population == MIN(population) over() THEN "MIN"
        WHEN population == MAX(population) over() THEN "MAX" ELSE "NA"
    END as "pop_stats"
FROM countries_by_population;

0
投票

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;
© www.soinside.com 2019 - 2024. All rights reserved.