我有这样一张桌子。我要输入的所有国家名称,人口编号,以及如果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;
首先,应该通过如下所示存储@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;
您可以使用窗口分析函数,例如DENSE_RANK()
和ORDER BY population
(默认)顺序中包含descending
子句的ascending
来通过从MIN
返回值来确定MAX
和1
值以便分别在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
顺便说一句,不要对导出的列值使用双引号,而应使用单引号。
使用over()
使其成为没有分区的窗口函数: