获取 INNER JOIN 中值的 SUM 会添加重复值

Getting a SUM of the values in INNER JOIN adds up duplicate values

我是 运行 一个查询,它每月从 table 中计算记录。 我正在尝试添加一个名为 "TotalPrice" 的额外列,我需要 'settle' table.

中所有价格的总和

我面临的问题是因为 INNER JOIN,'SUM' 的价格由于 INNER JOIN 返回的重复记录而累加了多个价格。有没有办法避免它并从唯一记录中获取价格总和?

SELECT
CONCAT(year(datetime), '-', month(datetime)) AS YearMonth,
COUNT (DISTINCT a.id) AS TOTAL, SUM(total_price) AS TotalPrice
FROM settle AS a with (nolock)
     INNER JOIN transfers b with (nolock) ON b.settleId = a.id 
     INNER JOIN Fdata AS c with (nolock) ON c.id=  b.data 
GROUP BY CONCAT(year(datetime), '-', month(datetime))

提前致谢。

sql 服务器 2008 之后:

with CTE as -- A CTE alows us to manipulate the data before we use it, like a derived table
(
select datetime, id, total_price, 
       row_number() over(partition by id, datetime order by total_price) as rn -- This creates a row number for each combo of id and datetime that appears
FROM settle AS a with (nolock)
     INNER JOIN transfers b with (nolock) ON b.settleId = a.id 
     INNER JOIN Fdata AS c with (nolock) ON c.id=  b.data 
)
SELECT CONCAT(year(datetime), '-', month(datetime)) AS YearMonth,
       COUNT (DISTINCT a.id) AS TOTAL, 
       SUM(total_price) AS TotalPrice
from CTE
where rn = 1 -- that row_number we created? This selects only the first one, removing duplicates
group by CONCAT(year(datetime), '-', month(datetime))