我有一個簡單的MySQL的SQL腳本,它輸出了我的行數隨着時間的推移特定表(基於時間字段的表)PostgreSQL的:行隨着時間的推移算
SELECT concat('M-', s.label)
, s.cnt
, @tot := @tot + s.cnt AS running_subtotal
FROM (SELECT DATE_FORMAT(t.created,'%y-%m') AS `label`
, COUNT(t.id) AS cnt
FROM `templates` t
GROUP BY `label`
ORDER BY `label`
) s
CROSS
JOIN (SELECT @tot := 0) i
現在我想將其遷移到PostgreSQL,但不知道如何將變量遷移到基於pg的語法。
內聲明的,當然,沒問題:這裏
SELECT TO_CHAR(t.created,'YYYY-MM') AS label
, COUNT(t.id) AS cnt
FROM templates t
GROUP BY label
ORDER BY label
任何人,誰可以幫我變的一部分?
這裏有一個簡單的表格與數據:
create TABLE "templates" (
"id" bigserial,
"title" varchar(2048) default NULL::character varying,
"created" timestamp,
PRIMARY KEY ("id")
);
insert into templates(title, created) values('test', '2011-03-01');
insert into templates(title, created) values('test 2', '2011-03-02');
insert into templates(title, created) values('test 3', '2011-03-03');
insert into templates(title, created) values('test 4', '2011-03-04');
insert into templates(title, created) values('test 5', '2011-03-05');
insert into templates(title, created) values('test 6', '2011-04-01');
insert into templates(title, created) values('test 7', '2011-04-02');
insert into templates(title, created) values('test 8', '2011-04-03');
insert into templates(title, created) values('test 9', '2011-04-04');
insert into templates(title, created) values('test 10', '2011-04-05');
… // 300 more for 2011-05
此查詢(基於與「創造」 -column記錄)的輸出的例子是:
M-11-03: 5 5 M-11-04: 5 10 (5 + 5) M-11-05: 300 310 (5 + 5 + 300)
(這是一個旋關閉Table statistics (aka row count) over time)
http://www.postgresql.org/docs/9.3/ static/tutorial-window.html – zerkms
你也許需要一些開窗功能。但是,如果您需要幫助,請通過添加索姆米數據來更新您的問題,以及您真正期待的結果。 – Houari
thx @Houari!爲了更容易識別目標,我添加了示例輸出。 –