使用联接和 Group by 子句更新查询
我有以下查询,我正在尝试使用总金额更新 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
I have the following query and I'm trying to update table1 with the Total amount.
Is there anyway to do this in 1 step?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用:
NULL
Use:
NULL
尝试:
正如注释中所指出的,即使 table2 中没有匹配项,上面的代码也会更新 table1 中的所有行 - 它将把列设置为 NULL。为了避免这种情况,请添加 WHERE 子句 - 请参阅 OMGPonies 的答案。
Try:
As has been pointed out in comments, the above will update all rows in table1 even if there is no match in table2 - in which it will set the column to NULL. To avoid that add a WHERE clause - see OMGPonies's answer.