加入两个表并使组和总和正确
JOINing two tables and make group and sums correct
几个小时以来一直在努力解决这个问题,非常感谢您的帮助!
所以我有两个表,transactions 和 transactions_rebuy
我的 SELECT 目标是 join/combine 这些表格并按日期对它们进行分组。
现在我有这个声明:
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" 列。
非常感谢对此的想法。
按日期对子查询进行分组,然后在该日期加入它们。
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
几个小时以来一直在努力解决这个问题,非常感谢您的帮助!
所以我有两个表,transactions 和 transactions_rebuy
我的 SELECT 目标是 join/combine 这些表格并按日期对它们进行分组。
现在我有这个声明:
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" 列。
非常感谢对此的想法。
按日期对子查询进行分组,然后在该日期加入它们。
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