簡體   English   中英

隨着時間推移,COUNT和GROUP BY

[英]COUNT and GROUP BY over time

我需要在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查詢的速度。 感謝您的任何幫助,您可以提供。

每年計數:

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)

每月計數器:

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)

參見postgres日期時間函數http://www.postgresql.org/docs/8.1/static/functions-datetime.html

我建議您使用提取功能,將年,月和日拆分為結果集中的離散列,然后根據需要進行分組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM