顧客の合計注文額を生成し、合計注文額を表す別の列と一緒に月ごとに列にグループ化するために使用するクエリがあります。
スキーマは次のとおりです。
temp=# \d+ customers;
Table "pg_temp_2.customers"
Column | Type | Modifiers | Storage | Description
------------+-----------------------------+-----------+----------+-------------
id | integer | not null | plain |
created_at | timestamp without time zone | | plain |
name | text | | extended |
Indexes:
"customers_pkey" PRIMARY KEY, btree (id)
Referenced by:
TABLE "orders" CONSTRAINT "orders_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES customers(id)
Has OIDs: no
Table "pg_temp_2.orders"
Column | Type | Modifiers | Storage | Description
-------------+-----------------------------+---------------+---------+-------------
id | integer | not null | plain |
created_at | timestamp without time zone | default now() | plain |
customer_id | integer | | plain |
amount | integer | | plain |
Indexes:
"orders_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
"orders_customer_id_fkey" FOREIGN KEY (customer_id) REFERENCES customers(id)
Has OIDs: no
便宜上、create table ステートメントを追加しました。
create temporary table customers ( id integer primary key, created_at timestamp without time zone, name text);
create temporary table orders ( id integer primary key, created_at timestamp without time zone, customer_id integer references customers(id));
私が使用しているクエリは次のとおりです。
SELECT
c.name,
sum(o.amount),
CAST(SUM(
CASE
WHEN date_trunc('month', o.created_at) BETWEEN '2012-10-01' AND ('2012-11-01'::date - '1 day'::interval)
THEN o.amount
ELSE 0
END
) / 100.0 AS MONEY) october2012,
CAST(SUM(
CASE
WHEN date_trunc('month', o.created_at) BETWEEN '2012-11-01' AND ('2012-12-01'::date - '1 day'::interval)
THEN o.amount
ELSE 0
END
) / 100.0 AS MONEY) as november2012
FROM orders o
INNER JOIN customers c ON o.customer_id = c.id
WHERE o.created_at >= '01 October 2012'
AND o.created_At < '01 December 2012'
GROUP BY
c.name
ORDER BY
october2012 desc;
その醜いケースステートメントを取り除くにはどうすればよいですか? これらのクエリを特定のタイム スライスにロールアップする、より洗練された方法が必要です。ウィンドウ関数を使用しようとしましたが、惨めに失敗しました。任意の支援をいただければ幸いです!
私はpostgresql 9.1を使用しています