O
O
Oleg Otkidach2020-01-02 00:24:20
MySQL
Oleg Otkidach, 2020-01-02 00:24:20

How to write a SQL query that will show the sum of data in column A for rows with a non-unique value in column B?

There is a table with columns:
- id;
- order_id;
- order_sum.
In the id column, the numbers are unique, but in the order_id column there are many duplicates - rows for which this order_id matches.
Task: compose such an SQL query, which will show the order_sum sum for rows with a non-unique order_id (or, alternatively, with a unique one).
We proceed from the fact that the order_sum of duplicates is the same.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Ezhgurov, 2020-01-02
@Allegro75

Get order_sum for each order_id that has duplicates:

SELECT
  order_id,
  MAX(order_sum) AS d_sum
FROM table
GROUP BY order_id
HAVING COUNT(id) > 1

It's just not possible to write order_sum in the list of fields - only those fields that are included in GROUP BY are allowed.
But you can use aggregate functions: MAX, MIN, AVG, SUM, COUNT.
Sum everything:
SELECT SUM(d_sum) AS a_sum
FROM (
  SELECT
    order_id,
    MAX(order_sum) AS d_sum
  FROM table
  GROUP BY order_id
  HAVING COUNT(id) > 1
) AS q

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question