使用case / if语句更新多个列?

时间:2017-07-06 09:24:29

标签: sql tsql

提前谢谢你:

我有一个table1:

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 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

1 个答案:

答案 0 :(得分: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
            )