总和2在行尾的同一个表中计数

时间:2017-07-06 13:52:23

标签: mysql

我使用下面的查询来生成下面的表格,我想要的是获得最后每行的总数

SELECT
    FreeText,
    COUNT(case Status WHEN 'BOOKING' then 1 else null end) AS Bookings,
    COUNT(case Status WHEN 'QUOTE' then 1 else null end) AS Quotes
FROM
    orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
WHERE
    OrderDate <= CURDATE()
AND OrderDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
AND FreeText IN ('user1','user2','user3')
AND STATUS IN ('BOOKING', 'QUOTE')
GROUP BY
    FreeText

以上产生了这个表:

FreeText | Bookings | Quote
User1    | 23       |11
User2    | 11       |17
User3    | 8        |4

我想要查询产生的内容:

FreeText | Bookings | Quote | Total
User1    | 23       |11     |34
User2    | 11       |17     |28
User3    | 8        |4      |12

非常感谢

2 个答案:

答案 0 :(得分:1)

COUNT(*)添加到查询中。

SELECT
    FreeText,
    COUNT(case Status WHEN 'BOOKING' then 1 else null end) AS Bookings,
    COUNT(case Status WHEN 'QUOTE' then 1 else null end) AS Quotes,
    COUNT(*) AS Total
FROM
    orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
WHERE
    OrderDate <= CURDATE()
AND OrderDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
AND FreeText IN ('user1','user2','user3')
AND STATUS IN ('BOOKING', 'QUOTE')
GROUP BY
    FreeText

答案 1 :(得分:1)

SELECT
    FreeText,
    COUNT(case Status WHEN 'BOOKING' then 1 else null end) AS Bookings,
    COUNT(case Status WHEN 'QUOTE' then 1 else null end) AS Quotes,COUNT(1) AS TOTAL
FROM
    orders
JOIN customers ON orders.CustomerNumber = customers.CustomerNumber
WHERE
    OrderDate <= CURDATE()
AND OrderDate > DATE_SUB(CURDATE(), INTERVAL 31 DAY)
AND FreeText IN ('user1','user2','user3')
AND STATUS IN ('BOOKING', 'QUOTE')
GROUP BY
    FreeText

尝试以上查询。

希望这会对你有所帮助。