在Oracle SQL中将批号插入表中

时间:2014-09-24 15:19:55

标签: sql oracle count

我有一个临时表,我插入从SELECT查询中提取的修改数据。

在这个临时表中,我想将行分组为批处理,因此我添加了一个名为“BATCH_NUM”的索引INT列

我希望实现的想法是这样的(比如我的SELECT语句中的1000个结果)。

伪代码

Batch Size = 100
Count = 0
For batch size in results set
Insert Into Temp Table (a , b , y , count)
Count++

当前SQL - 将静态值1输入BATCH_NUM列

INSERT INTO TEMP_TABLE
(
  ASSET_ID,
  PAR_PROM_INTEG_ID,
  IGNORE
  BATCH_NUM
)
SELECT carelevel.row_id, pstn.PROM_INTEG_ID, 
CASE
    WHEN promoprod.fabric_cd = 'Disabled'
    THEN 'Y'
    ELSE 'N'
END
'1'
FROM SIEBEL.S_ASSET carelevel
INNER JOIN SIEBEL.S_ASSET pstn
ON pstn.row_id = carelevel.par_asset_id
INNER JOIN SIEBEl.S_ASSET promotion 
ON pstn.prom_integ_id = promotion.integration_id
INNER JOIN SIEBEL.S_PROD_INT prod
ON prod.row_id = carelevel.prod_id
INNER JOIN SIEBEL.S_ORG_EXT bill
ON carelevel.bill_accnt_id = bill.row_id
INNER JOIN SIEBEL.S_INV_PROF invoice
ON bill.row_id = invoice.accnt_id
INNER JOIN SIEBEL.S_PROD_INT promoprod
ON promotion.prod_id = promoprod.row_id
WHERE prod.part_num = 'Testproduct'

但如果select语句有1000个结果,那么我希望BATCH_NUM来自每100条记录1,2,3,4,5,6,7,8,9,10。

可以这样做吗?

1 个答案:

答案 0 :(得分:3)

要将记录映射到批处理,您可能只想使用整数除法。或者稍微复杂一点,因为行从1编号,但像TRUNC((ROWNUM-1)/100)+1这样的东西就可以了。

以下是该映射的测试:

select level, trunc((ROWNUM-1)/100)+1 from dual connect by level <= 1000

结果:

ROWNUM  TRUNC((ROWNUM-1)/100)+1
1       1
...
100     1
101     2
...
200     2
201     3
...
...
900     9
901     10
...
1000    10

鉴于您的疑问:

INSERT INTO TEMP_TABLE
(
  ASSET_ID,
  PAR_PROM_INTEG_ID,
  IGNORE,
  BATCH_NUM
)
SELECT carelevel.row_id, pstn.PROM_INTEG_ID, 
CASE
    WHEN promoprod.fabric_cd = 'Disabled'
    THEN 'Y'
    ELSE 'N'
END,
TRUNC((ROWNUM-1)/100)+1,
-- ^^^^^^^^^^^^^^^^^^^^ 
-- map rows 1-100 to batch 1, rows 101-200 to batch 2 and so on
FROM SIEBEL.S_ASSET carelevel
INNER JOIN SIEBEL.S_ASSET pstn
ON pstn.row_id = carelevel.par_asset_id
INNER JOIN SIEBEl.S_ASSET promotion 
ON pstn.prom_integ_id = promotion.integration_id
INNER JOIN SIEBEL.S_PROD_INT prod
ON prod.row_id = carelevel.prod_id
INNER JOIN SIEBEL.S_ORG_EXT bill
ON carelevel.bill_accnt_id = bill.row_id
INNER JOIN SIEBEL.S_INV_PROF invoice
ON bill.row_id = invoice.accnt_id
INNER JOIN SIEBEL.S_PROD_INT promoprod
ON promotion.prod_id = promoprod.row_id
WHERE prod.part_num = 'Testproduct'