2008/01/20

交叉查詢語法@Oracle

用Oracle來建立交叉查詢表的語法如下:
 select to_char(Applydate, 'yyyy/mm' ) As Month, 
count(Decode(FormID, 'A01', SerialID, null )) AS A01,
count(Decode(FormID, 'A02', SerialID, null )) AS A02
from AFS_FLOW group by to_char(Applydate, 'yyyy/mm' )

這個語法可以將資料表:
   Applydate    FormID    SerialID
=========    ====== ========
2007/09/11    A01    T0000001
2007/09/12    A02    T0000002
2007/10/11    A01    T0000003
2007/10/12    A01    T0000004

變成這樣:
   Month         A01       A02
=========    ====== ======
2007/09    1 1
2007/10    2 0

這個語法有個缺點是你必須事先知道橫向欄位的名稱及數量,如果欄位是變數就無效了。

沒有留言: