SUM DISTINCT VALUE ON JOIN

1.6k views Asked by At
Order_ID
=========   
id  price
A   10
A   10
B   20
B   20
C   30
C   30
D   40
D   40

Client
==================  
Client  Name    id
1   ClientInc.  A
1   ClientInc.  A
1   ClientInc.  B
1   ClientInc.  B
1   ClientInc.  C
1   ClientInc.  C
1   ClientInc.  D
1   ClientInc.  D

I have two tables that I need to join (Order_ID and Client) and want to sum the price by distinct order_ID and create the report below:

Desired Solution
========================        
id  Name    Sum(Price)
1   ClientInc.  100

This is the current query I am using:

SELECT merchant,
name,
SUM(price)
FROM order_id a
JOIN client b
ON a.id = b.id
GROUP BY merchant, name

It is displaying the following output by summarizing every order_id, but the problem is that I want to SUM a distinct order ID:

Current Wrong Report
======================      
id  Name    Sum(Price)
1   ClientInc.  200
1

There are 1 answers

0
Teja On
SELECT merchant,
       name,
       SUM(price)
FROM ( SELECT DISTINCT id,price
         FROM order_id 
      ) a
JOIN client b
ON a.id = b.id
GROUP BY merchant, name;