使用MySQL

时间:2016-08-24 18:44:26

标签: mysql sql pivot

运行此查询时:

SELECT * FROM content_events

我得到这样一张桌子:

+------+-------------+
| hour | event_type  |
+------+-------------+
|    1 | loaded      |
|    2 | viewability |
|    3 | play        |
|    4 | loaded      |
|    1 | viewability |
|    2 | play        |
|    3 | loaded      |
|    4 | viewability |
|    5 | play        |
|    1 | loaded      |
|    2 | viewability |
+------+-------------+

我想转动它,所以我这样做:

+------+--------+------+-------------+
| hour | loaded | play | viewability |
+------+--------+------+-------------+
|    1 |      2 |      |           1 |
|    2 |        |    1 |           2 |
|    3 |      1 |    1 |             |
|    4 |      1 |      |           1 |
|    5 |        |    1 |             |
+------+--------+------+-------------+

要实现这一点,我应该首先创建一个名为value的虚拟列,每个单元格中包含“1”吗?换句话说,做一个像这样的选择:

SELECT *, 1 as value FROM content_events

将返回此信息:

+------+-------------+-------+
| hour | event_type  | value |
+------+-------------+-------+
|    1 | loaded      |     1 |
|    2 | viewability |     1 |
|    3 | play        |     1 |
|    4 | loaded      |     1 |
|    1 | viewability |     1 |
|    2 | play        |     1 |
|    3 | loaded      |     1 |
|    4 | viewability |     1 |
|    5 | play        |     1 |
|    1 | loaded      |     1 |
|    2 | viewability |     1 |
+------+-------------+-------+

然后使用该表做一个转轴?如果这个假设是正确的,那么数据透视查询将如何?

非常感谢任何帮助。

期待得到答案! :)

非常感谢!

1 个答案:

答案 0 :(得分:0)

Mysql /大多数rdbms使用条件聚合来做你想做的事。

SELECT
    hour
    ,COUNT(CASE WHEN event_type = 'loaded' tHEN event_type END) as loaded
    ,COUNT(CASE WHEN event_type = 'play' tHEN event_type END) as play
    ,COUNT(CASE WHEN event_type = 'viewability' tHEN event_type END) as viewability
FROM
    content_events t
GROUP BY
    hour
ORDER BY
    hour

sql-server为您解答。无需添加额外的1列

SELECT *
FROM
    content_events e
    PIVOT (
    COUNT(event_type)
    FOR event_type IN (loaded,play,viewability)
) p