mysql子查询COUNT以及GROUP BY YEAR

时间:2015-04-20 08:16:09

标签: mysql sql group-by subquery

找出最好的方法来解决这个问题。

这是我正在尝试做的事情:

SELECT 
YEAR(t.voucher_date) as period,
COUNT(t.id) as total_count, 
(SELECT COUNT(t2.id) FROM booking_global as t2 where t2.booking_status = 'CONFIRMED') as confirmed,
(SELECT COUNT(t3.id) FROM booking_global as t3 where t3.booking_status = 'PENDING') as pending
FROM booking_global t 
GROUP BY YEAR(t.voucher_date)

这会产生以下结果。

period total_count CONFIRMED PENDING
2014     4            5        3
2015     4            5        3

预期结果

period total_count CONFIRMED PENDING
  2014     4            3        1
  2015     4            2        2

在这里,我希望获得相应年份的CONFIRMED / PENDING计数,而不是计算所有状态。

我不确定如何将我的查询用作子查询并对结果运行另一个查询。

2 个答案:

答案 0 :(得分:1)

您可以拥有一个子查询来计算每年的booking_status。然后将结果加到表booking_global上。例如,

SELECT  YEAR(t.voucher_date)  voucher_date_year,
    COUNT(t.id) total_count,
    IFNULL(calc.confirmed_count, 0) confirmed_count,
    IFNULL(calc.pending_count, 0) pending_count
FROM    booking_global t
    LEFT JOIN
    (
        SELECT YEAR(voucher_date) voucher_date_year,
            SUM(booking_status = 'CONFIRMED') confirmed_count,
            SUM(booking_status = 'PENDING') pending_count
        FROM    booking_global
        GROUP   BY YEAR(voucher_date)
    ) calc ON calc.voucher_date_year = YEAR(t.voucher_date)
GROUP   BY YEAR(t.voucher_date)

答案 1 :(得分:1)

流动应该给你正确的结果

SELECT 
YEAR(t.voucher_date) as period,
COUNT(t.id) as total_count, 
(SELECT COUNT(t2.id) FROM booking_global as t2 where t2.booking_status = 'CONFIRMED' and YEAR(t2.voucher_date) = YEAR(t.voucher_date)) as confirmed,
(SELECT COUNT(t3.id) FROM booking_global as t3 where t3.booking_status = 'PENDING'  and YEAR(t3.voucher_date) = YEAR(t.voucher_date)) as pending
FROM booking_global t 
GROUP BY YEAR(t.voucher_date)