2

我有下表:

+----+------------+----------+------------------+
| 编号 | created_at | 平台 | 平台版本 |
+----+------------+----------+------------------+
| 1 | 1 | 麦克 | 1 |
| 2 | 2 | 麦克 | 1 |
| 3 | 3 | 麦克 | 2 |
| 4 | 4 | 麦克 | 2 |
| 5 | 5 | 麦克 | 2 |
| 6 | 5 | 麦克 | 3 |
| 7 | 2 | 窗户 | 1 |
| 8 | 2 | 窗户 | 2 |
| 9 | 3 | 窗户 | 3 |
| 10 | 3 | 窗户 | 1 |
| 11 | 4 | 窗户 | 2 |
| 12 | 4 | 窗户 | 3 |
| 13 | 5 | 窗户 | 4 |
| 14 | 5 | 窗户 | 1 |
| 15 | 6 | 窗户 | 2 |
| 16 | 6 | 窗户 | 3 |
+----+------------+----------+------------------+

我希望得到如下结果:

+-------------+----------------+---------------+--- ---------+
| 组数 | running_total | windows_total | created_at |
+-------------+----------------+---------------+--- ---------+
| 1 | 1 | 0 | 1 |
| 6 | 7 | 4 | 2 |
| 7 | 14 | 8 | 4 |
| 2 | 16 | 10 | 6 |
+-------------+----------------+---------------+--- ---------+

但是当我执行这个选择语句时:

选择组数,
       (@r := @r + group_count ) 作为 running_total,
       (@w := @w + ifnull(win_count, 0)) 作为 windows_total,
       t1.created_at
从(选择(@r:=0),
                COUNT( * ) AS group_count,
                平台,
                created_at
       从设备
       GROUP BY created_at DIV 2
      ) 作为 t1 左加入
      (SELECT COUNT( * ) AS win_count,
                created_at
       从设备
       WHERE 平台 = 'windows'
       GROUP BY created_at DIV 2
      ) AS t3 ON t1.created_at = t3.created_at

结果是这样的:

+-------------+----------------+---------------+--- ---------+
| 组数 | running_total | windows_total | created_at |
+-------------+----------------+---------------+--- ---------+
| 1 | 1 | 空 | 1 |
| 6 | 7 | 空 | 2 |
| 7 | 14 | 空 | 4 |
| 2 | 16 | 空 | 6 |
+-------------+----------------+---------------+--- ---------+

合并也不起作用。有人可以帮忙吗?谢谢。

4

1 回答 1

0

作为记录,我引用@eggyal的回答:

@w 最初为 NULL,因此将其添加到 IFNULL 的结果(无论该结果是什么)都会产生 NULL。
在子选择中给它一个初始值,就像你对 @r 所做的那样

SELECT group_count,
       (@r := @r + group_count ) AS running_total,
       (@w := @w + ifnull( win_count, 0 )) AS windows_total,
       t1.created_at
FROM  (SELECT   (@r:= 0),(@w:= 0),
                COUNT(*) AS group_count,
                platform,
                created_at
       FROM     devices
       GROUP BY created_at DIV 2
      ) AS t1 LEFT JOIN
      (SELECT   COUNT( * ) AS win_count,
                created_at
       FROM     devices
       WHERE    platform = 'windows'
       GROUP BY created_at DIV 2
      ) AS t3 ON t1.created_at = t3.created_at

这应该可以解决问题。

于 2012-07-22T23:09:21.937 回答