COUNT and GROUP BY over time
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 p开发者_如何学Cerform 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.
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)
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.
精彩评论