在汇总查询中获取汇总子值

时间:2019-01-19 18:37:51

标签: mysql sql

我有一个查询,需要在已经聚合的外部查询中显示聚合值。

考虑一个查询,该查询可提取某天记入贷方的帐户总数。

我想显示

  1. 总订单数
  2. “待处理”订单总数
  3. “未结”订单总数

这里的查询似乎很有意义,但是如下结果集所示,我显然没有使用正确的方法。 “ OPEN”列显示整个总数,“ PENDING”列为NULL。

我觉得我可能使用了错误的方法,这项工作有哪些选择?

SELECT s.created, COUNT(s.id) 'total_accounts_credited', SUM(s.withdrawal) 'total_amount_credited', 
(select count(s.id) WHERE s.status_id = 'OPEN')  total_open_credited,
(select count(s.id) WHERE s.status_id = 'PENDING') total_pending_credited
  FROM statements s 
WHERE s.status_id in ('OPEN', 'PENDING')
GROUP BY 
  YEAR(s.created), 
  MONTH(s.created), 
  DAY(s.created) 
  ORDER BY s.created DESC
;

结果:

+---------------------+-------------------------+-----------------------+---------------------+----------------------+
| created             | total_accounts_credited | total_amount_credited | total_open_credited | total_pending_credited |
+---------------------+-------------------------+-----------------------+---------------------+----------------------+
| 2019-01-19 00:00:00 |                   18050 |              20813.18 |               18050 |                 NULL |
| 2019-01-12 00:00:00 |                   18135 |              24768.43 |               18135 |                 NULL |
| 2019-01-10 09:00:27 |                      80 |               1497.75 |                  80 |                 NULL |
| 2019-01-09 09:20:55 |                      51 |                933.50 |                  51 |                 NULL |
| 2019-01-08 16:45:14 |                      10 |                187.50 |                  10 |                 NULL |
| 2019-01-05 18:21:00 |                   17588 |              16968.49 |               17588 |                 NULL |
| 2018-12-29 00:00:00 |                   17893 |              25404.18 |               17893 |                 NULL |
| 2018-12-28 15:23:04 |                       1 |                 35.00 |                   1 |                 NULL |
| 2018-12-22 00:00:00 |                   17353 |              17048.18 |               17353 |                 NULL |
| 2018-12-15 00:00:00 |                   16893 |              10181.34 |               16893 |                 NULL |
| 2018-12-08 00:00:00 |                   16220 |              99547.09 |               16220 |                 NULL |
| 2018-12-01 00:00:00 |                   15476 |              87699.59 |               15476 |                 NULL |
+---------------------+-------------------------+-----------------------+---------------------+----------------------+

0 个答案:

没有答案