數據庫----Oracle字段橫置

背景需要

  最近好久沒有寫文章了,主要原因因爲項目試運行了,自己每天都要關注項目運行情況,在穩定的時候去開發新的功能,但是在開發的時候,遇到一個問題難倒我了。具體的原因是,有時候客戶想要的數據是一條記錄展示完,但是我們在數據庫存的時候,通常都是一個存一條記錄。這就會有一個問題,什麼問題呢,比方說,客戶想要這臺設備24小時,每個小時的產量,以這樣的形式展示,
在這裏插入圖片描述
但是設備每個小時的產量在我們數據庫中都對應了一條記錄,是這樣的
在這裏插入圖片描述
我現在知道下面這所有的記錄,對應的單小時產量應該填在每一個時間段中,那麼我該怎麼做到?

解決方案

當時這個問題也是困擾了自己好長時間,本來自己寫了sql,結果發現總會出現一點問題,最後在網上找到比較好的解決方案,最後完美解決客戶需要,主要使用的函數,case when
最後的sql爲:

select a.orderchildid,a.deviceid,
sum(case a.datehour when '00' then a.quantity else null end )as t0,
sum(case a.datehour when '01' then a.quantity else null end )as t1,
sum(case a.datehour when '02' then a.quantity else null end )as t2,
sum(case a.datehour when '03' then a.quantity else null end )as t3,
sum(case a.datehour when '04' then a.quantity else null end )as t4,
sum(case a.datehour when '05' then a.quantity else null end )as t5,
sum(case a.datehour when '06' then a.quantity else null end )as t6,
sum(case a.datehour when '07' then a.quantity else null end )as t7,
sum(case a.datehour when '08' then a.quantity else null end )as t8,
sum(case a.datehour when '09' then a.quantity else null end )as t9,
sum(case a.datehour when '10' then a.quantity else null end )as t10,
sum(case a.datehour when '11' then a.quantity else null end )as t11,
sum(case a.datehour when '12' then a.quantity else null end )as t12,
sum(case a.datehour when '13' then a.quantity else null end )as t13,
sum(case a.datehour when '14' then a.quantity else null end )as t14,
sum(case a.datehour when '15' then a.quantity else null end )as t15,
sum(case a.datehour when '16' then a.quantity else null end )as t16,
sum(case a.datehour when '17' then a.quantity else null end )as t17,
sum(case a.datehour when '18' then a.quantity else null end )as t18,
sum(case a.datehour when '19' then a.quantity else null end )as t19,
sum(case a.datehour when '20' then a.quantity else null end )as t20,
sum(case a.datehour when '21' then a.quantity else null end )as t21,
sum(case a.datehour when '22' then a.quantity else null end )as t22,
sum(case a.datehour when '23' then a.quantity else null end )as t23
from biz_dev_order_phq a
where a.shiftdate=to_char(sysdate,'yyyy-MM-dd')
group by a.shiftdate,a.deviceid,a.orderchildid;

執行結果如下:
在這裏插入圖片描述

case when介紹

語法
  CASE search_expression

  WHEN expression1 THEN result1

  WHEN expression2 THEN result2

  ...

  WHEN expressionN THEN resultN

  ELSE default_result

  通常用時做條件判斷,根絕不同情況返回不同的結果,最簡單的方法就是實際與理想出現偏差的例子,
比如說,每個人都有一個每天都會響一次的鬧鐘,必須要設定個時間,如果你沒有設定時間,那麼系統就給你一個默認的每天早上8點響(只是例子),這個時候可能用nvl函數更好,但是case when不僅限於爲空,可以是滿足某個條件,比如通過表達式可以起到,定在0:00-6:00的我可以給他的結果賦爲7:00。這就是case when的好處。


補充

後來也是發現了oracle中有一個專門這樣的函數,當時做完忘記更新了,大家如果感興趣的話可以關注一下oracle裏面的這個函數 pivot

點我直達

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章