[英]Update Column where two values sum to equal zero in SQL Server
Since I'm not the greatest with SQL, I've run into a scenario where I must sum rows together based on their 'CtrlNo' and if the results return zero, then I do not need to display them. 由于我不是最擅长使用SQL,因此我遇到了一种情况,我必须根据行的“ CtrlNo”将行加在一起,如果结果返回零,则无需显示它们。
I'm able to sum these records and display the results like this.. 我能够对这些记录求和并显示这样的结果。
SELECT CtrlNo, SUM(Amt)/COUNT(DISTINCT CtrlNo)
FROM tContractsInTransit
GROUP BY CtrlNo
This will sum the distinct CtrlNo and the results are like this.. 这将对不同的CtrlNo求和,结果是这样的。
However, I need to update a column in the table based on where the CtrlNo has zero amt. 但是,我需要基于CtrlNo的amt为零的位置更新表中的列。
I have tried this.. 我已经尝试过了
UPDATE cit SET Paid = 'True'
FROM tContractsInTransit cit
WHERE (SELECT CtrlNo, SUM(Amt)/COUNT(DISTINCT CtrlNo)
FROM tContractsInTransit
GROUP BY CtrlNo) = 0
but receive this error.. 但收到此错误。
Msg 116, Level 16, State 1, Line 5
讯息116,第16级,州1,第5行
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.如果未使用EXISTS引入子查询,则只能在选择列表中指定一个表达式。
This will be the query that I use to select the records that aren't paid off.. 这将是我用来选择未还清记录的查询。
SELECT
[CtrlNo]
,[DealNoCat]
,[RefNo]
,[tCustomer].[CustomerName]
,[tBank].BankName
,[tFIManagers].[FIName]
,[Amt]
,[Days]
,[DaysOut]
FROM
[tContractsInTransit]
INNER JOIN
tFIManagers ON tFIManagers.FIManagerID = tContractsInTransit.FIManagerID
INNER JOIN
tBank ON tBank.BankID = tContractsInTransit.BankID
INNER JOIN
tCustomer ON tCustomer.CustomerID = tContractsInTransit.CustomerID
WHERE
PFX = @PFX
AND Paid = 'false'
GROUP BY
[CtrlNo]
,[DealNoCat]
,[RefNo]
,[tCustomer].[CustomerName]
,[tBank].BankName
,[tFIManagers].[FIName]
,[Amt]
,[Days]
,[DaysOut]
I have tried removing the 'WHERE Paid = 'false' and replacing Amt int he above select statement to.. 我试着删除“ WHERE Paid ='false”,并将上面的select语句替换为Amt int。
SUM(Amt)/COUNT(DISTINCT CtrlNo) AS Amt
but this returns everything. 但这会返回一切。
Any ideas is greatly appreciated! 任何想法都将不胜感激!
Use the HAVING-clause, which is equivalent to the WHERE-clause, but is applied outside the GROUP BY: 使用HAVING子句,该子句与WHERE子句等效,但应用于GROUP BY之外:
SELECT CtrlNo, SUM(Amt)/COUNT(DISTINCT CtrlNo)
FROM tContractsInTransit
GROUP BY CtrlNo
HAVING SUM(Amt)/COUNT(DISTINCT CtrlNo) = 0
I have found the solution and I'm posting just in case someone stumbles across this problem. 我已经找到了解决方案,并准备发布,以防万一有人偶然发现此问题。 The solution is fairly simple...
解决方案非常简单...
UPDATE tContractsInTransit
SET Paid = 'true'
FROM
tContractsInTransit cit
INNER JOIN
(SELECT CtrlNo
,SUM(Amt)/COUNT(DISTINCT CtrlNo) AS Tot
FROM tContractsInTransit
GROUP BY CtrlNo
HAVING SUM(Amt)/COUNT(DISTINCT CtrlNo) = 0) t
ON cit.CtrlNo = t.CtrlNo
This updates the paid column that returns all 0 results. 这将更新返回所有0结果的付费列。 Thanks to Dan for the Having clause suggestion.
感谢Dan提供的Haveing子句的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.