這篇文章主要介紹了postgresql數(shù)據(jù)合并,多條數(shù)據(jù)合并成1條的操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧。
對于主表中一條記錄,對應(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í)行計(jì)劃的合并連接
Merge Join
通常情況下,散列連接的效果比合并連接好,但如果源數(shù)據(jù)上有索引,或者結(jié)果已經(jīng)被排過序,在執(zhí)行排序合并連接時(shí),就不需要排序了,這時(shí)合并連接的性能會優(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í)行計(jì)劃中先對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í)行計(jì)劃中,可看到“Sort Key: dept01.deptno”,這就是對表dept01的id字段進(jìn)行排序。
以上為個人經(jīng)驗(yàn),希望能給大家一個參考。
文章來源:腳本之家
來源地址:https://www.jb51.net/article/205371.htm
申請創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!