iT邦幫忙

0

Postgre SQL to_timestamp的疑問

目前有一個專案要清整會員的生日資料,針對有異常的會員回壓長官指示的邏輯,過程中SQL產生錯誤,主要想針對這個錯誤發生的原因進一步了解。狀況說明如下。

圖1的SQL可以正常運作,但少去where內同一個欄位的條件,就會出現錯誤如圖2,後續做了圖3的測試,推測應該是資料內有異常,但想了解什麼情境有可能出現這種狀況。

只想知道這種狀況有可能發生的情境,以及背後資料可能存在的問題,再麻煩好心大神解惑,感激!

圖1 SQL
select member_id ::text, c_birth ::text,
case when to_char(to_timestamp(c_birth,'yyyymmdd'),'mm') = substr(c_birth,5,2) then to_timestamp(c_birth,'yyyymmdd')
else to_timestamp(substr(c_birth,1,6)::text||'01','yyyymmdd') + INTERVAL '1 MONTH - 1 day' end c_birth
from abcde.tb_cust_plus_member
where c_birth=c_birth
limit 10

圖1
https://ithelp.ithome.com.tw/upload/images/20181030/20112811CInfMBeOLb.png

圖2 SQL
select member_id ::text, c_birth ::text,
case when to_char(to_timestamp(c_birth,'yyyymmdd'),'mm') = substr(c_birth,5,2) then to_timestamp(c_birth,'yyyymmdd')
else to_timestamp(substr(c_birth,1,6)::text||'01','yyyymmdd') + INTERVAL '1 MONTH - 1 day' end c_birth
from abcde.tb_cust_plus_member
--where c_birth=c_birth
limit 10

圖2
https://ithelp.ithome.com.tw/upload/images/20181030/20112811R5g8XSlr3C.png

圖3 SQL
select
member_id ,
case when to_char(to_timestamp(c_birth,'yyyymmdd'),'mm') = substr(c_birth,5,2) then to_timestamp(c_birth,'yyyymmdd')
else to_timestamp(substr(c_birth,1,6)||'01','yyyymmdd') + INTERVAL '1 MONTH - 1 day' end c_birth
from
(
select '20180000'::text c_birth , '1001541' member_id
)

圖3
https://ithelp.ithome.com.tw/upload/images/20181030/201128116TtPk7aauY.png

如果不是limit 10的問題,一個看似無關痛癢的where,竟然影響了錯誤出現與否,確實蠻有趣的,卡一個等神人解答。
我自己憑空猜想,SQL先跑where才跑select,所以where有強迫資料庫去重新掃一遍c_birth欄位的可能?所以資料就正常了?@@...
應該是格式轉換失敗~
ty201457 iT邦新手 5 級 ‧ 2018-10-31 14:45:28 檢舉
不好意思,找到原因了,犯了一個頗初級的錯誤,資料的null值沒清到。
case when to_char(to_timestamp(c_birth,'yyyymmdd'),'mm') = substr(c_birth,5,2) then to_timestamp(c_birth,'yyyymmdd')
when c_birth is not null then to_timestamp(substr(c_birth,1,8)||'01','yyyymmdd') + INTERVAL '1 MONTH - 1 day'
else null end
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答