简体   繁体   中英

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.

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..

在此处输入图片说明

However, I need to update a column in the table based on where the CtrlNo has zero 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
Only one expression can be specified in the select list when the subquery is not introduced with 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..

 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:

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. Thanks to Dan for the Having clause suggestion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM