PostgreSQL
 sql >> Teknologi Basis Data >  >> RDS >> PostgreSQL

Postgres generate_series

Anda dapat menulis WITH permintaan untuk ini:

WITH month_amount AS
(
    SELECT
        sum(amount) AS amount,
        date_trunc('month', date) AS month
    FROM Amount
    WHERE user_id = 55 -- AND ...
    GROUP BY month
)
SELECT month, amount
FROM
    (SELECT generate_series(min(month), max(month), '1 month') AS month
    FROM month_amount) x
LEFT JOIN month_amount
USING (month)
ORDER BY month;

Contoh hasil:

SELECT * FROM amount WHERE user_id = 55;
 amount_id | user_id | amount |    date    
-----------+---------+--------+------------
         3 |      55 |      7 | 2011-03-16
         4 |      55 |      5 | 2011-03-22
         5 |      55 |      2 | 2011-05-07
         6 |      55 |     18 | 2011-05-27
         7 |      55 |      4 | 2011-06-14
(5 rows)

WITH month_amount ..
         month          | amount 
------------------------+--------
 2011-03-01 00:00:00+01 |     12
 2011-04-01 00:00:00+02 |       
 2011-05-01 00:00:00+02 |     20
 2011-06-01 00:00:00+02 |      4
(4 rows)


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Fungsi Postgres untuk Memvalidasi Alamat Email

  2. Rails tidak mengonversi zona waktu (PostgreSQL)

  3. Beberapa gabungan kiri pada beberapa tabel dalam satu kueri

  4. Kesalahan format tanggal postgresql

  5. Aplikasi yang berjalan di cron job Kubernetes tidak terhubung ke database di cluster Kubernetes yang sama