我正面临一个关于sql join的小问题
我有2张桌子
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->SMTPSecure = 'ssl';
$mail->Port = 465;
我需要像
这样的东西*1st table* *2nd table*
Reference Name Reference Amount
123 Test1 123 52
145 Test2 232 22
123 Test3 123 33
555 Test4 145 44
123 Test5 656 55
对我来说这看起来很简单,但它做了什么 - 它多次给我SUM参考是123所以它会给我(52 + 33)* 3
我应该使用什么来获得每个参考的唯一SUM?
THX!
编辑:
最终结果应该是
select distinct(a.reference), sum(b.amount) from 1st a left join 2nd b ON a.Reference = b.Reference group by a.reference
答案 0 :(得分:1)
在distinct
:
join
select a.reference, sum(b.amount)
from (select distinct reference from a) a left join
b
a.Reference = b.Reference
group by a.reference;
您几乎不需要将select distinct
与group by
一起使用。
答案 1 :(得分:0)
您的查询不正确,
你不应该使用distinct,因为我们有分组..
所以你很可能,
select a.reference, sum(b.amount) from 1st a
left join 2nd b ON a.Reference = b.Reference group by a.reference
答案 2 :(得分:0)
您还可以使用CTE解决问题:
WITH cte
AS
(
SELECT DISTINCT reference FROM 1st
)
SELECT a.reference, SUM(b.amount)
FROM cte a
LEFT JOIN 2nd b ON a.Reference = b.Reference
GROUP BY a.reference