我有以下查询,我正在尝试使用总金额更新table1。 无论如何都要一步到位吗?
select e.id
, p.id
, case
when count(distinct e.item) = 1 then 100
when count(distinct e.item) = 2 then 150
when count(distinct e.item) = 3 then 200
when count(distinct e.item) = 4 then 225
when count(distinct e.item) = 5 then 275
when count(distinct e.item) = 6 then 325
when count(distinct e.item) = 7 then 375
when count(distinct e.item) = 8 then 450
when count(distinct e.item) = 8 then 470
end as TotalPay
from table1 p
join table2 e on e.id = '111111'
and p.id=e.itemid
group by e.id, p.id
答案 0 :(得分:3)
使用:
UPDATE TABLE1
SET total = (SELECT CASE
WHEN COUNT(DISTINCT t2.item) = 1 THEN 100
WHEN COUNT(DISTINCT t2.item) = 2 THEN 150
WHEN COUNT(DISTINCT t2.item) = 3 THEN 200
WHEN COUNT(DISTINCT t2.item) = 4 THEN 225
WHEN COUNT(DISTINCT t2.item) = 5 THEN 275
WHEN COUNT(DISTINCT t2.item) = 6 THEN 325
WHEN COUNT(DISTINCT t2.item) = 7 THEN 375
WHEN COUNT(DISTINCT t2.item) = 8 THEN 450
WHEN COUNT(DISTINCT t2.item) = 9 THEN 470
END
FROM TABLE2 t2
WHERE t2.itemid = id
AND t2.id = '111111'
GROUP BY t2.id, t2.itemid)
WHERE EXISTS(SELECT NULL
FROM TABLE2 t
WHERE t.itemid = id
AND t.id = '111111')
NULL
答案 1 :(得分:1)
尝试:
update table1 p
set TotalPay =
(
select case
when count(distinct e.item) = 1 then 100
when count(distinct e.item) = 2 then 150
when count(distinct e.item) = 3 then 200
when count(distinct e.item) = 4 then 225
when count(distinct e.item) = 5 then 275
when count(distinct e.item) = 6 then 325
when count(distinct e.item) = 7 then 375
when count(distinct e.item) = 8 then 450
when count(distinct e.item) = 8 then 470
end as TotalPay
from table2 e where p.id=e.itemid
and e.id = '111111'
)
正如在注释中指出的那样,即使table2中没有匹配项,上面也会更新table1中的所有行 - 它将把列设置为NULL。为了避免添加WHERE子句 - 请参阅OMGPonies的答案。