Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 检索前12条记录,同时在给定字段中保持相同的值_Sql_Postgresql - Fatal编程技术网

Sql 检索前12条记录,同时在给定字段中保持相同的值

Sql 检索前12条记录,同时在给定字段中保持相同的值,sql,postgresql,Sql,Postgresql,我有一个表,其中标识符根据日期重复出现。我需要恢复每个标识符的前2条记录 表示例: identifier year month xxxx 2019 8 xxxx 2019 7 xxxx 2019 6 xxxx 2019 5 .... .... .. z

我有一个表,其中标识符根据日期重复出现。我需要恢复每个标识符的前2条记录

表示例:

  identifier      year      month   
     xxxx         2019        8 
     xxxx         2019        7 
     xxxx         2019        6 
     xxxx         2019        5 
     ....         ....        ..
     zzzz         2019        5
     zzzz         2019        4
     zzzz         2019        3
     zzzz         2019        2
     ....         ....        ..
预期结果:

   identifier      year      month
      xxxx         2019        8 
      xxxx         2019        7 
      zzzz         2019        5
      zzzz         2019        4
      other ...
我需要检索每个标识符的前两个记录,使用date子句这样做是无效的

提前谢谢

可以帮助您:

SELECT
    identifier, year, month
FROM (
    SELECT
        *,
        row_number() OVER (PARTITION BY identifier ORDER BY year DESC, month DESC)
    FROM
        mytable
) s
WHERE row_number <= 2
row\ U number将递增的行数添加到有序组分区中,在您的示例中是标识符。因此,如果您按年份和月份对组进行排序,最新的记录将得到行号1、2、3、。。。这些可以在以后过滤

可以帮助您:

SELECT
    identifier, year, month
FROM (
    SELECT
        *,
        row_number() OVER (PARTITION BY identifier ORDER BY year DESC, month DESC)
    FROM
        mytable
) s
WHERE row_number <= 2

row\ U number将递增的行数添加到有序组分区中,在您的示例中是标识符。因此,如果您按年份和月份对组进行排序,最新的记录将得到行号1、2、3、。。。之后可以对其进行筛选。

首先需要排序顺序。您要在哪个字段上排序?select的排序顺序是按标识符“年”、“月”进行的。首先需要排序顺序。您想在哪个字段上下单?select的排序顺序是按标识符、年、月。非常感谢S-Man。你完美地解决了我的问题。非常感谢S-Man。你完美地解决了我的问题。