[英]MySQL SUM of one column, Take only one of the same fields
Take a total for one column, but only need to take one row for the duplicate一列合计,但重复只需要一排
+---------------------------+--------+
| orderId | amount |
+---------------------------+--------+
| 2 | 2000 |
| 2 | 2000 |
| 5 | 2000 |
| 7 | 5000 |
+---------------------------+--------+
I hope to get a total of 9000 instead of 11000我希望总共得到9000而不是11000
I want the total value of different orderIds, not the total value of the same orderId, so I can't use group by.我要的是不同orderId的总值,而不是同一个orderId的总值,所以不能用group by。
Using MAX(amount)
with GROUP BY
will avoid the duplicate entries, then SUM()
will return the expected result: 将
MAX(amount)
与GROUP BY
将避免重复输入,然后SUM()
将返回预期结果:
SELECT SUM(Amount) AS SumAmount
FROM (
SELECT orderId, MAX(amount) AS Amount
FROM TableName
GROUP BY orderId
) A
Please find the working demo on db<>fiddle 请在db <> fiddle上找到有效的演示
尝试这个:
select orderId, sum(amount) from tmp_tbl group by orderId;
If you are using MySQL 8+, then ROW_NUMBER
provides one option here: 如果您使用的是MySQL 8+,则
ROW_NUMBER
在此处提供一个选项:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY orderId ORDER BY orderId) rn
FROM yourTable
)
SELECT SUM(amount)
FROM cte
WHERE rn = 1;
The ordering used by ROW_NUMBER
above is arbitrary, but this is a good general approach in case you want to use different logic later on regarding which of the duplicate records to include in the sum. 上面
ROW_NUMBER
所使用的顺序是任意的,但这是一种很好的通用方法,以防您以后要使用不同的逻辑来考虑将哪些重复记录包括在总和中。
SELECT SUM(Amount) AS SumAmount FROM TablName where orderid = ( SELECT Distinct(orderId) FROM TableName ) SELECT SUM(Amount)AS SumAmount FROM TablName,其中orderid =(SELECT Distinct(orderId)FROM TableName)
I have corrected the query 我已更正查询
I think the best query would be 我认为最好的查询是
SELECT SUM(Amount) AS SumAmount, COUNT(orderId)
FROM yourTable
GROUP BY orderId
HAVING COUNT(orderId) > 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.