postgresql數(shù)據(jù)合并,多條數(shù)據(jù)合并成1條的操作
對于主表中一條記錄,對應(yīng)明細(xì)表中的96條數(shù)據(jù),每一條數(shù)據(jù)相隔15分鐘,明細(xì)中沒96條數(shù)據(jù)對應(yīng)主表中的一個日期trade_date,并且每條明細(xì)中有一個字段start_time, 即明細(xì)中每96條數(shù)據(jù)中第一條數(shù)據(jù)中start_time為00:00,
第二條為00:15,第三條為00:30,依次類推,直到23:45 ,現(xiàn)在要將明細(xì)表中的96條數(shù)據(jù)合并成24條,即第一條數(shù)據(jù)中start_time為00:00,第二條為01:00,第三條為02:00
sql:select max(de.bid_num) report_num,concat(to_char(to_timestamp(concat(ru.trade_date,' ',de.start_time), 'YYYY-MM-DD HH24:mi') :: TIMESTAMP WITHOUT TIME ZONE, 'HH24 '),':00') dd from quote_trade_rule ru LEFT JOIN quote_trade_rule_detail de on ru.trade_rule_id = de.trade_rule_id WHERE 1 = 1 AND ru.market_id ='a29c81ed-2baf-4c42-881a-f1e64a41e1b0' AND to_char(ru.trade_date, 'YYYY-MM-DD') ='2018-10-17' AND ru.rule_type ='2' GROUP BY dd ,trade_date ORDER BY dd,trade_date
將10條主表數(shù)據(jù)對應(yīng)的960條明細(xì)數(shù)據(jù)合并成如下24條數(shù)據(jù):
補(bǔ)充:Postgresql中執(zhí)行計劃的合并連接
Merge Join
通常情況下,散列連接的效果比合并連接好,但如果源數(shù)據(jù)上有索引,或者結(jié)果已經(jīng)被排過序,在執(zhí)行排序合并連接時,就不需要排序了,這時合并連接的性能會優(yōu)于散列連接。
下面示例中,people的id字段和dept01的depto字段都有索引,且從索引掃描的數(shù)據(jù)已經(jīng)排好序,可以直接走M(jìn)erge Join:
highgo=# explain select people.id from people,dept01 where people.id=dept01.deptno; QUERY PLAN ------------------------------------------------------------------------------------------------- Merge Join (cost=0.86..64873.59 rows=1048576 width=4) Merge Cond: (people.id = dept01.deptno) -> Index Only Scan using people_pkey on people (cost=0.44..303935.44 rows=10000000 width=4) -> Index Only Scan using idx_deptno on dept01 (cost=0.42..51764.54 rows=1048576 width=2) (4 行記錄)
刪除dept01上的索引,會發(fā)現(xiàn)執(zhí)行計劃中先對dept01排序后在走M(jìn)erge Join,示例如下:
highgo=# explain select people.id from people,dept01 where people.id=dept01.deptno; QUERY PLAN ------------------------------------------------------------------------------------------------- Merge Join (cost=136112.80..154464.29 rows=1048576 width=4) Merge Cond: (people.id = dept01.deptno) -> Index Only Scan using people_pkey on people (cost=0.44..303935.44 rows=10000000 width=4) -> Materialize (cost=136112.36..141355.24 rows=1048576 width=2) -> Sort (cost=136112.36..138733.80 rows=1048576 width=2) Sort Key: dept01.deptno -> Seq Scan on dept01 (cost=0.00..16918.76 rows=1048576 width=2) (7 行記錄)
上面執(zhí)行計劃中,可看到“Sort Key: dept01.deptno”,這就是對表dept01的id字段進(jìn)行排序。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持本站。如有錯誤或未考慮完全的地方,望不吝賜教。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。