下面是我的选择查询
#include <stdio.h>
#include <stdlib.h>
int main(){
char **p;
p = (char**) malloc (2*sizeof(char*));
*p = (char*) malloc (2*sizeof(char));
**p = 'k';
**(p+1) = 'f';
*p = *p+1;
**p = 'c';
**(p+1) = 'd';
}
我想基于customerid的count(*)值更新表“ custtable”中的“级别”和“折扣”列
如果count(*)<2,则级别= 1,折扣= 10
如果count(*)> 3,则级别= 3,折扣= 20
如果为0,则均为0
如何在Mysql中执行此操作?
答案 0 :(得分:0)
由于您没有提供测试用例,所以我自己做了。可能并不完美,但是比 none 更好。
SQL> create table custtable (customerid number, c_level number, discount number);
Table created.
SQL> insert into custtable
2 select 1, null, null from dual union all
3 select 2, null, null from dual;
2 rows created.
SQL>
SQL> create table orders (customerid number, orderno number);
Table created.
SQL> insert into orders
2 select 1, 100 from dual union all
3 select 3, 300 from dual;
2 rows created.
SQL>
SQL> create table orderitem (orderno number);
Table created.
SQL> insert into orderitem
2 select 100 from dual union all
3 select 300 from dual;
2 rows created.
这是您的查询:
SQL> select d.customerid, count(*) as count
2 from orderitem i join orders d on d.orderno = i.orderno
3 group by d.customerid;
CUSTOMERID COUNT
---------- ----------
1 1
3 1
SQL>
为了执行 update ,我建议使用MERGE
语句,例如
SQL> merge into custtable t
2 using (select d.customerid, count(*) as cnt
3 from orderitem i join orders d on d.orderno = i.orderno
4 group by d.customerid
5 ) x
6 on (t.customerid = x.customerid)
7 when matched then update set
8 t.c_level = case when x.cnt < 2 then 1
9 when x.cnt > 3 then 3
10 when x.cnt = 0 then 0
11 end,
12 t.discount = case when x.cnt < 2 then 10
13 when x.cnt > 3 then 20
14 when x.cnt = 0 then 0
15 end;
1 row merged.
结果:
SQL> select * From custtable;
CUSTOMERID C_LEVEL DISCOUNT
---------- ---------- ----------
1 1 10
2
SQL>
答案 1 :(得分:0)
您可以在UPDATE
语句中使用相关子查询来做到这一点:
update custtable
set (level, discount) =
(select (case when count(*) = 0 then 0
when count(*) <= 2 then 1
else 3
end) as level,
(case when count(*) = 0 then 0
when count(*) <= 2 then 10
else 20
end) as discount
from Orderitem oi join
orders o
on oi.orderno = o.orderno
where o.customerid = custtable.customerId
);
请注意,Oracle使您可以同时在update
中更新多个列。
我也略微更改了逻辑,因此包括了“ 2”的计数。