随着时间的推移进行计数和分组
我需要在 PostgreSQL 中按天、周、月等创建销售报告。我有以下表格设置:
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)
我需要创建一个 SQL 查询,返回给定时间范围内购买给定产品的次数。也就是说,我需要查询给定产品 ID 在特定月份、日期、年份等中出现在采购订单项目中的次数。在之前的问题中,我学习了如何使用 date_trunc() 将我的 TIMESTAMP 列截断为我关心的那段时间。现在我面临着如何正确执行 COUNT 和 GROUP BY 的问题。
我已经尝试使用 COUNT(XXX) 和 GROUP BY XXX 的各种组合进行多次查询,但似乎从未达到我的预期。有人可以指导我如何构建这个查询吗?我更像是一名 Java 开发人员,所以我仍在加快 SQL 查询的速度。感谢您提供的任何帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每年计数:
每月计数:
Count per year:
Counter per month:
请参阅 postgres 日期时间函数 http://www.postgresql.org/docs/ 8.1/static/functions-datetime.html
我建议您使用提取函数,将年、月和日拆分为结果集中的离散列,然后根据您的要求进行分组。
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.