在資料庫中查詢資料時,往往會存在著某一項資料的不連續,如下:
可以看出,存在著連續的時間資料,但是當具體到某一類資料時,有時會因為各類原因導致資料缺失或者不連續。
那麼,在這樣的情況下,如何解決這類問題?
方法有很多:
其中,最簡單但並不推薦的就是採用union
語法插入某個缺失的資料
以上面的資料為例:
這樣的話就可以插入這一條資料union
select to_date(
'2015-01-01'
,'yyyy-mm-dd')as
"time",0
as"value"
但是,這將會導致一系列問題,因此並不推薦使用
另乙個辦法就是採用case when..then...else then...else...end
的語法來對資料進行判斷,並組合。
結果如下with
t1 as
(select
distinct
"date"
as"time"
from
table
order
by"time"),
t2 as
(select
"date"
,"value"
from
table
where
"type"
='demo'
order
by"time"
)select
*from t1,t2
那麼 ,如何將資料組合成連續的呢?我們一步一步來實現:
首先
結果如下with
t1 as
(select
distinct
"date"
as"time"
from
table
order
by"time"),
t2 as
(select
"date"
,"value"
from
table
where
"type"
='demo'
order
by"time"
)select t1.
"time"
,t2.
"time"
,case
when t1.
"time"
=t2.
"time"
then t2.
"value"
else
0end
from t1,t2
這樣就可以用0
替代許多重複的資料
接下來使用distinct
,sum
來清除重複項,並求出相應值的總和
結果如下with
t1 as
(select
distinct
"date"
as"time"
from
table
order
by"time"),
t2 as
(select
"date"
,"value"
from
table
where
"type"
='demo'
order
by"time"
)select
distinct t1.
"time"
,sum
(case
when t1.
"time"
=t2.
"time"
then t2.
"value"
else
0end
)from t1,t2
group
by t1.
"time"
order
by t1.
"time"
與之前的查詢結果相比較,很顯然,資料被重新組合成連續的,多出的資料所對應的值為0
,並沒有影響
當然,這些連續的資料首先是基於資料庫中的某一字段是連續的,如果該欄位本來就是不連續的,那麼就需要我們手動將它改變成連續的,使用union
在之前的**中插入缺失的資料即可
第三種方法也是採用case when..then...else then...else...end
的語法來對資料進行判斷,並組合。
與上乙個方法相比較的話,該方法的連續時間主要依賴於資料庫,無法自主union
資料
python鏈結postgresql資料庫
安裝完畢以後就可以寫 測試了,我的測試環境是windows下安裝了postgresql資料庫,執行的python 在虛擬機器的ubuntu下,其實拿到windows執行也是沒問題的,如下 import psycopg2 import psycopg2.extras database port 543...
postgresql 迴圈插入資料
plsql直接迴圈插資料當然比 裡迴圈插要快很多,只是pl sql的語法不怎麼統一,不同的資料庫語法上有些細微的差異,很頭疼 postgresql 迴圈插入資料 do declare v idx integer 1 begin while v idx 10 loop v idx v idx 1 in...
nodejs連線postgreSQL資料庫
nodejs連線pg資料庫有兩種方式,一種是直接連線 操作 斷開 還有一種是使用連線池,這種方式可以有效提公升多併發的效率 下邊是使用兩種不同方式的測試 var pgopt require pg 使用連線池 function connectpgwithpool var pgpool new pgop...