加入时的DISTINCT值

时间:2017-08-29 19:26:13

标签: sql join sum distinct distinct-values

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

我需要加入两个表(Order_ID和Client),并希望通过不同的order_ID对价格求和并创建以下报告:

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

这是我正在使用的当前查询:

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

它通过汇总每个order_id显示以下输出,但问题是我想要SUM一个不同的订单ID:

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

1 个答案:

答案 0 :(得分:0)

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;