使用DB2 UDB OLAP函数
2008-09-03 16:28:17 来源:WEB开发网使用顺序表将两条记录布置到一行上
假设该表的结构和数据如下:
createTABLEVEHICLE_ACCIDENT(
ACCIDENT_IDINTNOTNULL,
TAG_NUMBERchar(10),
TAG_STATEchar(2));
insertINTOVEHICLE_ACCIDENTVALUES(1,’123456’,’IL’),(1,’234567’,’IL’),(1,’34567TT’,’WI’);
(为了简单起见,这里省略了其他列)。注意,在一起事故中可能牵涉到不止两辆车。这就要求将两条记录布置到一行上,像这样(当牵涉到 3 辆车时):
TAG_NUMBER_1TAG_STATE_1TAG_NUMBER_2TAG_STATE_2
----------------------------------------------
123456 IL 234567 IL
3456TT WI
通过使用 ROW_NUMBER() ,这一点很容易实现:
WITHVEHICLE_ACCIDENT_RN(ACCIDENT_ID,ROWNUM,TAG_NUMBER,TAG_STATE)AS
(selectACCIDENT_ID,ROW_NUMBER()OVER()ASROWNUM,TAG_NUMBER,TAG_STATE
FROMVEHICLE_ACCIDENT)
select
LEFT_SIDE.TAG_NUMBERASTAG_NUMBER_1,
LEFT_SIDE.TAG_STATEASTAG_STATE_1,
RIGHT_SIDE.TAG_NUMBERASTAG_NUMBER_2,
RIGHT_SIDE.TAG_STATEASTAG_STATE_2
FROM
(selectL.*,(L.ROWNUM+1)/2ASPAGENUMFROMVEHICLE_ACCIDENT_RNLwhereMOD(ROWNUM,2)=1)ASLEFT_SIDE
LEFTOUTERjoin
(selectR.*,(R.ROWNUM+1)/2ASPAGENUMFROMVEHICLE_ACCIDENT_RNRwhereMOD(ROWNUM,2)=0)ASRIGHT_SIDE
ONLEFT_SIDE.PAGENUM=RIGHT_SIDE.PAGENUM
whereLEFT_SIDE.ACCIDENT_ID=1AND(RIGHT_SIDE.ACCIDENT_ID=1ORRIGHT_SIDE.ACCIDENT_IDISNULL)
更多精彩
赞助商链接