我可以在一个查询中执行几个WHERE LIMIT语句吗?

时间:2014-03-04 22:06:05

标签: sql postgresql window-functions

我遇到过这样的事情:

      country    | year | total
  ---------------+------+-------
   Romania       | 2004 |    20
   United States | 2004 |    19
   Japan         | 2004 |     9
   Russia        | 2004 |     8
   China         | 2004 |     3
   Latvia        | 2004 |     1
   Canada        | 2004 |     1
   Ukraine       | 2004 |     1
   China         | 2008 |    24
   United States | 2008 |    20
   Japan         | 2008 |     7
   Romania       | 2008 |     7
   Uzbekistan    | 2008 |     1
   Spain         | 2008 |     1
   South Korea   | 2008 |     1
   North Korea   | 2008 |     1
   Russia        | 2012 |    12
   China         | 2012 |    12
   United States | 2012 |    10
   Great Britain | 2012 |     8
   South Korea   | 2012 |     1
   Ukraine       | 2012 |     1

我的问题是我正在尝试执行单个查询,该查询将从总列中按行排列每行3行。

结果如下:

      country    | year | total
  ---------------+------+-------
   Romania       | 2004 |    20
   United States | 2004 |    19
   Japan         | 2004 |     9
   China         | 2008 |    24
   United States | 2008 |    20
   Japan         | 2008 |     7
   Russia        | 2012 |    12
   China         | 2012 |    12
   United States | 2012 |    10

如果我执行了3个单独的查询,每个查询的LIMIT为3并使用

,我可以得到我想要的数据
WHERE year = 2004, WHERE year = 2008, and WHERE year  = 2012

但我无法弄清楚是否可以使用一个查询?一些见解将不胜感激!

2 个答案:

答案 0 :(得分:3)

在子查询中使用窗口函数row_number()

SELECT *
FROM  (
   SELECT *, row_number() OVER (PARTITION BY year ORDER BY total DESC) AS rn
   FROM   tbl
   ) sub
WHERE rn < 4

答案 1 :(得分:1)

如果这是t-sql,我会使用行号并按年份进行分区。

select country, year, total from (
    select *, rn = row_number() over (partition by year order by total desc)
    from tbl
) where rn < 4