How to remove duplicates and sum in SQL Server?
In SQL Server, you can use the GROUP BY and SUM functions to achieve deduplication and summing operations. The specific method is as follows:
- Group the data by the columns that need to be deduplicated.
- Use the SUM function to calculate the sum for each group.
- You can use the HAVING clause to filter out groups that do not meet the conditions.
For example, suppose there is a table named Orders with columns such as OrderID, CustomerID, and OrderAmount. If we want to deduplicate and sum the OrderAmount based on CustomerID, we can use the following SQL statement:
SELECT CustomerID, SUM(OrderAmount) AS TotalAmount
FROM Orders
GROUP BY CustomerID
This will return each CustomerID along with the deduplicated sum of TotalAmount.