多次在同一个表中选择两列

时间:2014-03-26 11:29:49

标签: sql postgresql union union-all sql-limit

我正在尝试使用以下查询显示第二大和第二少人口国家/地区的国家/地区人口。我找到了为这些国家选择人口的方法,但我找不到任何有效的方法来实施国名选择。

Select  Max(population) 
From country Where population < (Select max (population) From country)
Union
Select Min(population)
From country where population > (select Min(population) from country) ;

我找到了为第二大/第二人口最少的国家选择国家和人口的方法,但问题是我不能在两个选项上使用union和2个ORDER BY(每个选择一个)。< / p>

知道我能做些什么来解决我的问题吗? 注意:我正在使用Postgres

4 个答案:

答案 0 :(得分:1)

通过使用窗口功能,你可以这样做:

with t as (
  select population,
         row_number() over (order by population desc) mx,
         row_number() over (order by population asc) mn
  from country)
select 'second most population', population from t where mx = 2
union all
select 'second least population', population from t where mn = 2;

答案 1 :(得分:1)

select *
from (
    select country, population
    from
        (
            select country, population
            from country
            order by population
            offset 1 limit 1
        ) s

    union

    select country, population
    from
        (
            select country, population
            from country
            order by population desc
            offset 1 limit 1
        ) q
) s

答案 2 :(得分:0)

找到解决方案:

(SELECT name, population 
FROM country 
ORDER BY population Desc 
LIMIT 1 OFFSET 1
) 
UNION
(
SELECT name, population 
FROM country 
ORDER BY population Asc 
LIMIT 1 OFFSET 1);

我只需要括号......

答案 3 :(得分:0)

更多更简单,更快捷:

(
SELECT population
FROM   country
ORDER  BY 1
OFFSET 1
LIMIT  1
)
UNION ALL
)
SELECT population
FROM   country
ORDER  BY 1 DESC
OFFSET 1
LIMIT  1
);

,您可以对LIMIT查询的各个分支使用OFFSETUNION。只需使用括号。详细信息:
Combining two SQL SELECT statements on the same table

确保在population上设置索引,以便在更大的表格中实现这一目标。

并使用UNION ALL,因为您不想折叠重复项。更快,实际上正确