2015-08-25 28 views
3

我有一個簡單的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

+0

http://www.postgresql.org/docs/9.3/ static/tutorial-window.html – zerkms

+0

你也許需要一些開窗功能。但是,如果您需要幫助,請通過添加索姆米數據來更新您的問題,以及您真正期待的結果。 – Houari

+0

thx @Houari!爲了更容易識別目標,我添加了示例輸出。 –

回答

0

對於日期格式化,可以使用M-YY-MM作爲格式化字符串來獲取,例如:M-11-03。 而使用aggragate countwindow function

SELECT distinct TO_CHAR(created,'M-YY-MM'), 
     COUNT(id) OVER (ORDER BY TO_CHAR(created,'YY-MM')) 
FROM templates 
ORDER BY 1 

SQL FIDDLE

+0

@a_horse_with_no_name查看此[SQLFIDDLE](http://www.sqlfiddle.com/#!15/eb08a/2)以查看結果,獨特' – Houari

+0

真的不錯的代碼!但我不知道如何獲得第二列(滾動總數)。我需要做一個總和(count_field)OVER(ORDER BY date_field))的連接嗎? –

相關問題