简体   繁体   中英

Duplicates in Sum SQL Server 2014

The code I have works great except for it sums the deposit amount for multiple dates instead of only the corresponding date and account. For example:

Account #: 123 / Date: 01/01/2012 / Deposit Required: $100 / Deposit: $100

Account #: 123 / Date: 01/20/2012 / Deposit Required: $100 / Deposit: $100

Query Results:

Account #: 123 / Date: 01/01/2012 / Deposit Required: $100 / Deposit: $200

Account #: 123 / Date: 01/20/2012 / Deposit Required: $100 / Deposit: $200

It is the same persons account but with two different dates. The deposit amount should only sum the amount corresponding to the account # & date. Thanks for any help!

SELECT ca.fdorgunit AS Facility
, pt.fdmedrecnum AS Account
, ca.fddos AS DOS
, Cast(iv.fdinnetdeposit/100.0 as decimal(10,2)) AS [Deposit Required]
, Sum(Case When pa.fddescription = 'Deposit' Then Cast(pa.fdpayadjamount/100.0 as decimal(10,2)) Else 0 END) AS Deposit
FROM OPENQUERY (VISION, 'SELECT * FROM de.tbinsverification') AS iv
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM ci.tbcase') AS ca
ON iv.fdcase = ca.id
JOIN OPENQUERY (VISION, 'SELECT * FROM de.tbpatient') AS pt
ON pt.id = ca.fdpatient
LEFT JOIN OPENQUERY (VISION, 'SELECT * FROM ar.tbpayadjmaster') AS pa
ON pa.fdpatient = pt.id
WHERE iv.fdinnetdeposit is not Null AND iv.fdinnetdeposit <> '0' AND ca.fdcasestatus = 'Performed'
GROUP BY ca.fdorgunit, ca.fddos, iv.fdinnetdeposit, pt.fdmedrecnum

Below is how it should look in the table but the current query is returning a Deposit of $200 for both 10/10/16 & 10/20/16 dates:

Facility | Account |  DOS     | Deposit Required | Deposit
1        |   1234  | 10/10/16 |    $100          |  $100
1        |   1234  | 10/20/16 |    $100          |  $100

如果要获取“按需存款 ”和“按月和按年存款”的总和,请在GROUP BY中尝试此操作。

GROUP BY ca.fdorgunit, MONTH(ca.fddos), YEAR(ca.fddos), iv.fdinnetdeposit, pt.fdmedrecnum

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