0

under Postgres 9.3 I am trying to run a query to summarize some data from table a:

| Entry date-Date | Customer ID-charvar | received-Boolean | Processed-Boolean | finalized-Boolean | billed-Date |

I would like use count(case when) to count all the records by the current week, month, then all of time into table b:

|report date | Total Received Weekly | Received Monthly | Received all of time | so on...

I am having a difficult time wrapping my head around how to write that query. I have thought about extracting the week day and month number to determine my records to sum for each length of time but then how would I make it repeatable without having to change the dates so I could automate it to run weekly through either PgAgent or CRON?

asked Aug 4, 2015 at 18:01

1 Answer 1

0

Too long for a comment now: I don't speak PGSQL so try adapting the following for your date extraction functions:

SELECT
 MAX(CurrentWeekCount) As CurrentWeekCount
 ,MAX(CurrentMonthCount) As CurrentMonthCount
 ,MAX(AllCount) As AllCount
FROM
(

count all the records by the current week

 SELECT
 COUNT(CustomerID) As CurrentWeekCount
 ,NULL As CurrentMonthCount
 ,NULL As AllCount
 FROM YourTable
 WHERE DATEPART(week, YourDateColumn) = DATEPART(week, GETDATE())
 UNION ALL

month

SELECT
 NULL As CurrentWeekCount
 ,COUNT(CustomerID) As CurrentMonthCount
 ,NULL As AllCount
 FROM YourTable
 WHERE DATEPART(month, YourDateColumn) = DATEPART(month, GETDATE())
 UNION ALL

all of time

 SELECT
 NULL As CurrentWeekCount
 ,NULL As CurrentMonthCount
 ,COUNT(CustomerID) As AllCount
 FROM YourTable
) x
answered Aug 4, 2015 at 21:32

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.