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

Kecualikan periode yang tumpang tindih dalam fungsi agregat waktu

Bagaimana dengan ini:

WITH
   /* get all time points where something changes */
   points AS (
       SELECT "startDate" AS p
       FROM temp_period
       UNION SELECT "endDate"
       FROM temp_period
   ),
   /*
    * Get all date ranges between these time points.
    * The first time range will start with NULL,
    * but that will be excluded in the next CTE anyway.
    */
   inter AS (
      SELECT daterange(
                lag(p) OVER (ORDER BY p),
                p
             ) i
      FROM points
   ),
   /*
    * Get all date ranges that are contained
    * in at least one of the intervals.
    */
   overlap AS (
      SELECT DISTINCT i
      FROM inter
         CROSS JOIN temp_period
      WHERE i <@ daterange("startDate", "endDate")
   )
/* sum the lengths of the date ranges */
SELECT sum(age(upper(i), lower(i)))
FROM overlap;

Untuk data Anda itu akan kembali:

┌──────────┐
│ interval │
├──────────┤
│ 576 days │
└──────────┘
(1 row)


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Rails:PG::InsufficientPrivilege:ERROR:izin ditolak untuk hubungan schema_migrations

  2. Bagaimana cara mengembalikan hanya waktu kerja dari reservasi di PostgreSql?

  3. Membuat UUID di Postgres untuk pernyataan Sisipkan?

  4. Bagaimana cara menambahkan sumber data PostgreSQL ke WildFly 9.0?

  5. Cara Memantau PostgreSQL menggunakan Nagios