添加到查询以获取以前结果SQL的总和

时间:2016-04-19 14:58:04

标签: mysql sql

我目前有一个提供下面结果集的查询,我现在需要添加到此查询中以提供所有销售底部的总计。我不知道该怎么做。

当前查询:

SELECT
    product,
    COUNT(OrderNumber) AS CountOf
FROM
    orders
WHERE
    STATUS = 'booking' AND
    Date(OrderDate) <= CURDATE() AND 
    Date(OrderDate) > DATE_SUB(CURDATE(),INTERVAL 30 DAY)

GROUP BY
    product
ORDER BY CountOf DESC

当前结果集:

product| count
-----------------------
pd1  | 3
pd4  | 1
pd2  | 1

期望的结果集=

product| count
-----------------------
pd1  | 3
pd4  | 1
pd2  | 1
Total | 5

2 个答案:

答案 0 :(得分:1)

也许你可以添加一个UNION,以及一个总额为SELECT的。像这样:

SELECT
    product,
    COUNT(OrderNumber) AS CountOf
FROM
    orders
WHERE
    STATUS = 'booking' AND
    Date(OrderDate) <= CURDATE() AND 
    Date(OrderDate) > DATE_SUB(CURDATE(),INTERVAL 30 DAY)
GROUP BY
    product
UNION
SELECT 'Total', count(OrderNumber) AS CountOf
FROM   orders
WHERE
    STATUS = 'booking' AND
    Date(OrderDate) <= CURDATE() AND 
    Date(OrderDate) > DATE_SUB(CURDATE(),INTERVAL 30 DAY)
ORDER BY CountOf DESC;

答案 1 :(得分:0)

尝试在同一个表上使用内部联接,由于每一侧的列数不正确,因此联合不起作用。

初始选择有2个设置列,其中第二个选择(在联合之后)没有。