SELECT
SUM(p.price + c.price) AS product_weekly_total
FROM t_product_purchase p
LEFT JOIN
t_coupon_purchase c on c.storepkid=p.storepkid ";
WHERE
(p.purchasedatetime BETWEEN '2014-12-27 00:00:01' AND '2015-01-02 23:59:59') OR
(c.purchasedatetime BETWEEN '2014-12-27 00:00:01' AND '2015-01-02 23:59:59')
GROUP BY
p.storepkid
ORDER BY
product_weekly_total DESC LIMIT 0,5
我希望通过价格和cprice字段的总和获得前5名最高总记录。但是上面的查询在结果中给了我错误的金额。
如果我从上面的查询中删除't_coupon_purchase'表并使用't_product_purchase'来解除查询,那么它会给出正确数量的正确结果。
请让我知道我在查询中做了什么错误,或者我应该以其他方式写出来,因为我不知道。请提供一些帮助。
----编辑 - 01JAN2015 ---- SQL小提琴我的查询 http://www.sqlfiddle.com/#!2/0d4523/8
这里我已经提到了每个商店的总数,因此有助于与查询结果进行比较。
5 = 67 + 68 + 115 = 250
1 = 57 + 50 + 75 + 66 = 248
3 = 70 + 144 = 214
2 = 23 + 100 + 22 + 27 = 172
4 = 15 + 7 + 105 = 127
9 = 34
7 = 33
答案 0 :(得分:1)
以下查询适用于我。
SELECT t.storepkid, SUM(t.price) AS product_weekly_total
FROM
(
SELECT storepkid AS storepkid, price AS price
FROM t_product_purchase
WHERE purchasedatetime BETWEEN '2014-12-27 00:00:01' AND '2015-01-02 23:59:59'
UNION ALL
SELECT storepkid, price FROM t_coupon_purchase
WHERE purchasedatetime BETWEEN '2014-12-27 00:00:01' AND '2015-01-02 23:59:59'
) t
GROUP BY storepkid
ORDER BY product_weekly_total DESC LIMIT 0,5
这个链接提供了SQL小提琴:http://www.sqlfiddle.com/#!2/f269b/46
答案 1 :(得分:0)
首先,我认为你的第5行t_coupon_purchase c on c.storeid=p.storeid ";
有拼写错误。 ";
不应该在那里。
此外,您在日期中的约束应该只有一个OR
。代码未执行,因为在您的第二个OR
之后,没有其他约束。
由于您是LEFT JOINing,您可能会添加一个带有来自LEFT JOINed表的不匹配NULL的数字。此外,我不认为您可以在查询中订购结果。你可以试试下面的内容,看看你得到了什么?
select storeid, product_weekly_total from
(
SELECT
p.storeid, SUM(coalesce(p.price,0) + coalesce(c.cprice,0)) AS product_weekly_total
FROM t_product_purchase p
LEFT JOIN
t_coupon_purchase c on c.storeid=p.storeid
WHERE
(p.purchasedate BETWEEN '2014-12-27' AND '2015-01-03') OR
(c.cpurchasedate BETWEEN '2014-12-27' AND '2015-01-03')
GROUP BY
p.storeid
) as X
ORDER BY
product_weekly_total DESC LIMIT 0,5
所以你实际上是在订购总和的最终结果。
由于
修改强> 从您在小提琴中看到的数据模型,行:
(11, 7, 33.00, '2015-12-01 01:01:01'),
(12, 1, 75.00, '2015-12-01 07:07:57'),
(13, 5, 68.00, '2015-12-01 22:22:00'),
(14, 9, 34.00, '2015-12-01 09:06:00'),
(15, 2, 27.00, '2015-12-01 17:06:00');
由于日期是2015年12月1日,不会被退回。