Sql 在内部联接中获得一个值的总和会增加重复的值

Sql 在内部联接中获得一个值的总和会增加重复的值,sql,sql-server,sql-server-2008,sql-server-2005,Sql,Sql Server,Sql Server 2008,Sql Server 2005,我正在运行一个查询,它每月从表中统计记录。 我正在尝试添加一个额外的列,名为“TotalPrice”,我需要“结算”表中所有价格的总和 我面临的问题是由于内部联接,由于内部联接返回的重复记录,价格的“总和”将多个价格相加。有并没有一种方法可以避免这种情况,并从独特的记录中获得价格的总和 SELECT CONCAT(year(datetime), '-', month(datetime)) AS YearMonth, COUNT (DISTINCT a.id) AS TOTAL, SUM(tota

我正在运行一个查询,它每月从表中统计记录。 我正在尝试添加一个额外的列,名为“TotalPrice”,我需要“结算”表中所有价格的总和

我面临的问题是由于内部联接,由于内部联接返回的重复记录,价格的“总和”将多个价格相加。有并没有一种方法可以避免这种情况,并从独特的记录中获得价格的总和

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 server 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))

我假设每个
id
每个
datetime
都有一个
total\u price
?是的,它是一个。。我要一个月的所有总价的总和。。。我不能使用SUM(不同的总价),因为多个记录可能有相同的价格。非常感谢它的有效性,你也能给我解释一下吗?