PostgreSQL query to count/group by day and display days with no data

后端 未结 5 1071
醉酒成梦
醉酒成梦 2020-12-07 16:34

I need to create a PostgreSQL query that returns

  • a day
  • the number of objects found for that day

It\'s important that every sing

5条回答
  •  萌比男神i
    2020-12-07 16:51

    Extending Gordon Linoff's helpful answer, I would suggest a couple of improvements such as:

    • Use ::date instead of date_trunc('day', ...)
    • Join on a date type rather than a character type (it's cleaner).
    • Use specific date ranges so they're easier to change later. In this case I select a year before the most recent entry in the table - something that couldn't have been done easily with the other query.
    • Compute the totals for an arbitrary subquery (using a CTE). You just have to cast the column of interest to the date type and call it date_column.
    • Include a column for cumulative total. (Why not?)

    Here's my query:

    WITH dates_table AS (
        SELECT created::date AS date_column FROM sharer_emailshare WHERE showroom_id=5
    )
    SELECT series_table.date, COUNT(dates_table.date_column), SUM(COUNT(dates_table.date_column)) OVER (ORDER BY series_table.date) FROM (
        SELECT (last_date - b.offs) AS date
            FROM (
                SELECT GENERATE_SERIES(0, last_date - first_date, 1) AS offs, last_date from (
                     SELECT MAX(date_column) AS last_date, (MAX(date_column) - '1 year'::interval)::date AS first_date FROM dates_table
                ) AS a
            ) AS b
    ) AS series_table
    LEFT OUTER JOIN dates_table
        ON (series_table.date = dates_table.date_column)
    GROUP BY series_table.date
    ORDER BY series_table.date
    

    I tested the query, and it produces the same results, plus the column for cumulative total.

提交回复
热议问题