Reputation: 12039
I have a need to create sales reports by day, week, month, etc. in PostgreSQL. I have the following tables setup:
tbl_products:
id INT
name VARCHAR
tbl_purchase_order:
id INT
order_timestamp TIMESTAMP
tbl_purchase_order_items:
id INT
product_id INT (FK to tbl_products.id)
order_id (FK to tbl_purchase_order.id)
I need to create a SQL query that returns the number of times a given product has been purchased within a given time frame. That is, I need to query the number of times a given product ID appears in a purchase order item in a specific month, day, year, etc. In an earlier question I learned how to use date_trunc() to truncate my TIMESTAMP column to the period of time I'm concerned about. Now I'm faced with how to perform the COUNT and GROUP BY properly.
I've tried several queries using various combinations of COUNT(XXX) and GROUP BY XXX but never seem to come up with what I'm expecting. Can someone give me guidance as to how to construct this query? I'm more of a Java developer, so I'm still getting up to speed on SQL queries. Thanks for any help you can provide.
Upvotes: 1
Views: 1692
Reputation: 8534
See the postgres datetime functions http://www.postgresql.org/docs/8.1/static/functions-datetime.html
I would suggest that you use the extract function, to split the year, month and day into discreet columns in the result set, and then group by as per your requirements.
Upvotes: 1
Reputation:
Count per year:
SELECT oi.product_id,
extract(year from po.order_timestamp) as order_year
count(*)
FROM purchase_order_items oi
JOIN purchase_order po ON po.id = oi.order_id
GROUP BY extract(year from po.order_timestamp)
Counter per month:
SELECT oi.product_id,
extract(month from po.order_timestamp) as order_month
extract(year from po.order_timestamp) as order_year
count(*)
FROM purchase_order_items oi
JOIN purchase_order po ON po.id = oi.order_id
GROUP BY extract(year from po.order_timestamp),
extract(month from po.order_timestamp)
Upvotes: 4