我有一个像调用temp1(Original Image)
的sql表+ --------- + --------- + ------ + ---------- +
| ClientKey | LoginFrom | Month | Tran_Count |
+ --------- + --------- + ------ + ---------- +
| 1 | E | 201603 | 2 |
| 3 | A | 201504 | 3 |
| 3 | X | 201506 | 105 |
| 3 | A | 201602 | 3 |
| 3 | X | 201509 | 3 |
| 3 | A | 201512 | 1 |
| 3 | W | 201508 | 3 |
| 3 | W | 201505 | 17 |
| 3 | W | 201507 | 14 |
| 3 | W | 201504 | 34 |
| 3 | W | 201509 | 1 |
| 3 | X | 201504 | 170 |
| 3 | W | 201506 | 29 |
| 3 | W | 201510 | 1 |
| 3 | X | 201505 | 51 |
| 3 | X | 201508 | 11 |
| 3 | A | 201603 | 1 |
| 3 | X | 201510 | 3 |
| 3 | X | 201507 | 44 |
| 4 | W | 201601 | 2 |
| 4 | E | 201601 | 4 |
| 4 | A | 201602 | 1 |
| 4 | E | 201602 | 19 |
+ --------- + --------- + ------ + ---------- +
我想总结一下表(name_summary),如(Original Image):
+ --------- + ---------------- + ---------------- + ---------------- + --- +
| ClientKey | A type in 201504 | A type in 201505 | W type in 201504 | ... |
+ --------- + ---------------- + ---------------- + ---------------- + --- +
| 3 | 3 | | 34 | ... |
+ --------- + ---------------- + ---------------- + ---------------- + --- +
我尝试过以下sql代码
update master_summary
set
A_type_in_201504=case when temp1.LoginFrom='A' and temp1.[month]='201504' then temp1.tran_count end,
A_type_in_201505=case when temp1.LoginFrom='A' and temp1.[month]='201505' then temp1.tran_count end,
W_type_in_201504=case when temp1.LoginFrom='W' and temp1.[month]='201504' then temp1.tran_count end,
W_type_in_201505=case when temp1.LoginFrom='W' and temp1.[month]='201505' then temp1.tran_count end
from master_summary
inner join
temp1
on
master_summary.clientkey=temp1.clientkey
我认为我错了。当我尝试使用多个条件进行单列更新时,它给出了正确的结果。但是多列更新具有不同的多重条件,它无法正常工作..
是谁能帮助我?答案 0 :(得分:0)
您需要使用max()
进行汇总,并使用子查询加入汇总查询:
update master_summary
set
A_type_in_201504=s.A_type_in_201504
, A_type_in_201505=s.A_type_in_201505
, W_type_in_201504=s.W_type_in_201504
, W_type_in_201505=s.W_type_in_201505
from master_summary
inner join (
select
clientkey,
, A_type_in_201504=max(case
when temp1.LoginFrom='A' and temp1.[month]='201504' then temp1.tran_count end)
, A_type_in_201505=max(case
when temp1.LoginFrom='A' and temp1.[month]='201505' then temp1.tran_count end)
, W_type_in_201504=max(case
when temp1.LoginFrom='W' and temp1.[month]='201504' then temp1.tran_count end)
, W_type_in_201505=max(case
when temp1.LoginFrom='W' and temp1.[month]='201505' then temp1.tran_count end)
from temp1
group by clientkey
) s
on master_summary.clientkey=s.clientkey