【问题标题】:mysql Sub queries in COUNT along with GROUP BY YEARCOUNT 中的 mysql 子查询以及 GROUP BY YEAR
【发布时间】:2015-04-20 08:16:09
【问题描述】:

在找出执行此操作的最佳方法时遇到了一些麻烦。

这是我想要做的:

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 计数,而不是获取所有状态的计数。

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

【问题讨论】:

  • @Dhaval 和 John 你的两个答案都给出了预期的结果,但是哪一个是有效的,我怎样才能将它转换为 codeigniter 活动记录

标签: mysql sql group-by subquery


【解决方案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)

【讨论】:

    【解决方案2】:

    您可以有一个子查询来计算每年的每个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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 2021-12-19
      • 2018-09-17
      相关资源
      最近更新 更多