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

时间:2018-01-09 12:48:08

标签: sql sql-server sql-server-2008 sql-server-2005

我正在运行一个查询,该查询从表中按月计算记录。 我正在尝试添加一个名为" TotalPrice"的额外列,我需要来自'和#39;的所有价格的总和。表

我面临的问题是因为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))

提前致谢。

1 个答案:

答案 0 :(得分:2)

sql server 2008起:

SELECT CASE WHEN member_id = 6 THEN id ELSE 0 END last_id FROM my_table ORDER BY id DESC LIMIT 1;
+---------+
| last_id |
+---------+
|       0 |
+---------+