加入两个表并使组和总和正确

时间:2016-10-30 00:24:27

标签: mysql sql-server join group-by cross-join

现在试图解决这个问题几个小时了,非常感谢你的帮助!

所以我有两个表,transaction和transactions_rebuy

我的SELECT目标是加入/组合这些表并按日期对它们进行分组。

现在我有这样的声明:

SELECT tr.SoldDate, SUM(tr.TotalAmount) as SumByReceipt,
COUNT(DISTINCT(tr.`ForsNr`)) as TotalCustomers, rebuy.RebuySum
FROM transactions tr   
CROSS JOIN (
SELECT SUM(TotalAmount) as RebuySum
    FROM transactions_rebuy
    WHERE SoldDate BETWEEN '2016-10-22' AND '2016-10-27'
    ) as rebuy
WHERE tr.SoldDate BETWEEN '2016-10-22' AND '2016-10-27' 
GROUP by tr.SoldDate
ORDER by tr.SoldDate DESC

这给了我以下结果:

SaldDatum SumByReceipt TotalCustomers RebuySum

2016-10-27 54855.8001       99        10435.9997
2016-10-26 41749.8009       76        10435.9997
2016-10-25 46626.8001       79        10435.9997
2016-10-24 38678.8017       76        10435.9997
2016-10-22 30351.9997       48        10435.9997

问题是" RebuySum"列按以上所有日期的总和进行分组。作为" SumByReceipt",我希望它按日期分组,而不是每行的总和。

我已经尝试过分组和总结,然后让它起作用,但随后又搞砸了SumByReceipt"" SumByReceipt"而是专栏。

非常感谢这方面的想法。

1 个答案:

答案 0 :(得分:0)

按日期对子查询进行分组,然后在日期加入它们。

SELECT tr.SoldDate, SUM(tr.TotalAmount) as SumByReceipt,
        COUNT(DISTINCT(tr.`ForsNr`)) as TotalCustomers, IFNULL(rebuy.RebuySum, 0) RebuySum
FROM transactions tr   
LEFT JOIN (
    SELECT SoldDate, SUM(TotalAmount) as RebuySum
    FROM transactions_rebuy
    WHERE SoldDate BETWEEN '2016-10-22' AND '2016-10-27'
    GROUP BY SoldDate
    ) as rebuy
ON tr.SoldDate = rebuy.SoldDate
WHERE tr.SoldDate BETWEEN '2016-10-22' AND '2016-10-27' 
GROUP by tr.SoldDate
ORDER by tr.SoldDate DESC