sql >> データベース >  >> RDS >> PostgreSQL

Postgres次/前行SQLクエリ

    Q1:FIRST_VALUE / LAST_VALUE

    Q2:PARTITION BY(Roman Pekarがすでに提案したように)

    ここでフィドルを参照

    SELECT
      DISTINCT i.id AS id,
      i.userid AS userid,
      i.itemname AS itemname,
      COALESCE(LEAD(i.id)        OVER (ORDER BY i.created DESC)
              ,FIRST_VALUE(i.id) OVER (ORDER BY i.created DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS nextitemid,
      COALESCE(LAG(i.id)         OVER (ORDER BY i.created DESC)
              ,LAST_VALUE(i.id)  OVER (ORDER BY i.created DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS previtemid,
      COALESCE(LEAD(i.id)        OVER (PARTITION BY i.userid ORDER BY i.created DESC)
              ,FIRST_VALUE(i.id) OVER (PARTITION BY i.userid ORDER BY i.created DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS nextuseritemid,
      COALESCE(LAG(i.id)         OVER (PARTITION BY i.userid ORDER BY i.created DESC)
              ,LAST_VALUE(i.id)  OVER (PARTITION BY i.userid ORDER BY i.created DESC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)) AS prevuseritemid,
      i.created AS created
    FROM items i
      LEFT JOIN users u
      ON i.userid = u.id
    ORDER BY i.created DESC;
    


    1. LAST_DAY()がMariaDBでどのように機能するか

    2. エラー1045(28000)を克服する方法:ユーザー'ODBC' @'localhost'(パスワードを使用:NO)のアクセスが永続的に拒否されました

    3. ZendDbを使用したネストされた選択

    4. TRY CATCH 内の 1 つのステートメントから複数のエラー メッセージを取得する