2016-08-15 105 views
-1

如何插入值與第二列值輸出表中插入第三列值如何基於第二列值

我想根據2列值輸出

查詢插入一個3列的值

insert into table1 (id, type, desc) 
values 
select id#, 
case 
when CUSTOMER_CODE = 'I' then (select type# from customertype where typecode = 'abc') 
when CUSTOMER_CODE = 'L' and LEN(NUMBER) > 0 then (select type# from customertype where typecode = 'def') 
end, 
case 
when CUSTOMER_TYPE = 'M' and type = 1 then 'dwcerf' 
when CUSTOMER_TYPE = 'O' and type = 2 then 'scef' 
End 
from table2 

型= 1型= 2是第二列的輸出

如何做到這一點,請建議

+2

請以文字顯示當前結果和預期結果 – TheGameiswar

+0

發佈此消息時超過3,700點,但信息不足。你已經在這裏呆了很長時間,知道沒有任何細節沒有人能真正幫助你。發佈一個適當的問題,你會得到一個正確的答案。 –

+0

更糟的是......你今天已經發布了這個問題一次,並且因爲重複而關閉。傷心... –

回答

0

您可以使用子查詢:

insert into table1 (id, type, desc) 
SELECT *, 
     case 
      when CUSTOMER_TYPE = 'M' and type = 1 then 'dwcerf' 
      when CUSTOMER_TYPE = 'O' and type = 2 then 'scef' 
      End 
FROM (
    select id#, 
    case 
    when CUSTOMER_CODE = 'I' then (select type# from customertype where typecode = 'abc') 
    when CUSTOMER_CODE = 'L' and LEN(NUMBER) > 0 then (select type# from customertype where typecode = 'def') 
    end as [type] 
    from table2 
    ) as p 
0

您可以使用插入與第2列的值,然後與先前選擇第三列值的更新。我不知道您的插入的上下文,但是您是否沒有在運行此查詢的地方提供此信息?

0

如果您需要中間變量來參與進一步的計算,請使用APPLY。

insert into table1 (id, type, desc) 
select id#, 
    ca.var, 
    case 
    when CUSTOMER_TYPE = 'M' and ca.var = 1 then 'dwcerf' 
    when CUSTOMER_TYPE = 'O' and ca.var = 2 then 'scef' 
    End 
from table2 
cross apply (
    select var = case 
      when CUSTOMER_CODE = 'I' then (select type# from customertype where typecode = 'abc') 
      when CUSTOMER_CODE = 'L' and LEN(NUMBER) > 0 then (select type# from customertype where typecode = 'def') 
     end) ca 

希望typecode是獨一無二的customertype,否則你會得到一個錯誤。

相關問題