Mysql 使用case和sum语句更新
运行此查询后,我收到一条错误消息,表明group函数的使用无效。我很确定在case语句之后,我需要一个“AS amount”或“AS I.amount”,但是mySQl也不喜欢这些。有什么建议吗Mysql 使用case和sum语句更新,mysql,sql,Mysql,Sql,运行此查询后,我收到一条错误消息,表明group函数的使用无效。我很确定在case语句之后,我需要一个“AS amount”或“AS I.amount”,但是mySQl也不喜欢这些。有什么建议吗 update INVITATION AS i LEFT JOIN REGISTRATION AS r on i.id=r.INVITATION_id LEFT JOIN FUNDING AS f on r.id=f.REGISTRATION_id SET i.funding_travel_a
update INVITATION AS i
LEFT JOIN REGISTRATION AS r on i.id=r.INVITATION_id
LEFT JOIN FUNDING AS f on r.id=f.REGISTRATION_id
SET i.funding_travel_amount = SUM(case
when f.category = "Other" then sum(amount)
when f.category = "Airfare" then sum(amount)
when f.category = "Mileage" then sum(amount)
else 0 end), i.funding_travel = "Custom"
WHERE i.funding_hotel = "Prepaid"
and i.funding_travel = "None"
and i.funding_per_diem = "None"
and (f.category = "Other" OR f.category ="Airfare" OR f.category= "Mileage")
and f.id is not null;
或许,您应该删除金额前的总和 这是您的查询格式,因此更具可读性(至少对我而言): 有一个问题很明显——sum中有sum语句。我会用一个相关的子查询来写这个:
update INVITATION
SET funding_travel_amount =
(select SUM(case when f.category = "Other" then amount
when f.category = "Airfare" then amount
when f.category = "Mileage" then amount
else 0
end)
from Registration r join
Funding f
on r.id=f.REGISTRATION_id and
invitation.id = r.invitation_id
),
funding_travel = "Custom"
WHERE funding_hotel = "Prepaid" and
funding_travel = "None" and
funding_per_diem = "None"
这并不完全相同,因为即使没有可用的类别,它也会更新金额。你可以在
的where
上附加一个条件来解决这个问题。我不明白如果你选择的行只有这三个值,为什么你会使用的CASE…当时。我还尝试了以下方法:正如你所知,我现在很新。在I.id=r.INVITATION\u id LEFT JOIN上以r注册时更新邀请在r.id=f.REGISTRATION\u id设置i.FUNDING\u travel\u amount=(选择SUM(SUM)(SUM(f.category=“Other”+f.category=“Airfare”+f.category=“Miledge”))、i.FUNDING\u travel=“Custom”,其中i.FUNDING\u hotel=“预付费”和i.FUNDING\u travel=“无”和i.FUNDING\u per\u diem=“无”和(f.category=“其他”或f.category=“Airfare”或f.category=“Miledge”)和f.id不为空;好的,我建议您共享您的表架构定义和一些示例数据,以及所需的结果。然后人们可以快速帮助您。@Gordon,当我尝试您的查询时,我得到的错误是读取组函数的无效使用。@user2232926…我最初回答得太快了。我看到了总和()
在一个sum()
中,这触发了我的响应。我将使用一个相关的子查询来编写查询,我现在将其作为答案包含在内。
update INVITATION
SET funding_travel_amount =
(select SUM(case when f.category = "Other" then amount
when f.category = "Airfare" then amount
when f.category = "Mileage" then amount
else 0
end)
from Registration r join
Funding f
on r.id=f.REGISTRATION_id and
invitation.id = r.invitation_id
),
funding_travel = "Custom"
WHERE funding_hotel = "Prepaid" and
funding_travel = "None" and
funding_per_diem = "None"