2017-07-06 65 views
0

预先感谢您:用case/if语句更新多列?

我有一个表1:

id  || batches || IC_chips 

DRG001 || JHL001 || layer1 
DRG001 || JHL001 || layer2 
DRG001 || JHL001 || layer3 
DRG001 || JHL001 || layer4 
DRG001 || JHL001 || layer5 
DRG001 || JHL001 || layer6 
DRG001 || JHL002 || layer7 
DRG001 || JHL002 || layer8 
DRG001 || JHL002 || layer9 
DRG001 || JHL002 || layer10 
POQ001 || ADG001 || layer1 
POQ001 || ADG001 || layer2 
POQ001 || ADG001 || layer3 
POQ001 || ADG001 || layer4 
POQ001 || ADG001 || layer5 
POQ001 || ADG001 || layer6 

输出表:

ID  || print_batch_1 || Print_batch_2 || Count_print_batch_1 || Count_print_batch_2 || Batch_count 
DRG001 || JHL001   || JHL002   || 06     || 04     || 02 
POQ001 || ADG001   || Null   || 06     || Null     || 01 

我用update语句尝试过,但我面临的一个问题,当他们不止一个打印批次。

这是我试图用代码:

update tab 
set Count_name=b.Count_name 
,batch_count=b.batch_count 
from 
table1 tab 
inner join 
(
select Name, count(batches) as Count_name, count(distinct batches) as 
batch_count 
from table1 
group by batches) b 
on tab.batches=b.batches 
+0

提示:这是有帮助的标记同时与相应的软件(MySQL和甲骨文,DB2数据库的问题。 ..)和版本,例如'的SQL服务器2014'。语法和功能的差异往往会影响答案。请注意,'tsql'缩小了选择范围,但不指定数据库。 – HABO

+0

我正在使用MSSQL 2012 –

回答

1

请试试这个 -

update tab B 
set Count_name = a.batches, batch_count = batch_cnt 
from (
      select batches, count(*) batch_cnt 
      from table1 A 
      where a.batches = b.batches 
     ) 
where 
    exists (
       select 1 
       from table1 A 
       where a.batches = b.batches 
      ) 
+1

我收到此错误Amey:**关键字'where'附近的语法不正确。** –

+0

此代码适用于Oracle SQL,不知道表'tab'的结构。另请尝试将别名分配给'from'子句中使用的子查询。 – Amey

+0

好吧,谢谢 –