SQL查询 - 计数和总和 - 运动统计

时间:2017-12-19 08:58:53

标签: mysql

我正在运行一个小项目,我尝试从日志中计算事件数。日志中的每一行(转移到表中)包含如下表所示的数据。

我有一张桌子如下。

|NN | XX | YY | ZZ |
+---+----+----+----+
| A |  A |  B |    |
| B |  B |  A |  C |
| A |  A |  C |  B |
| C |  C |  B |  A |
| C |  C |  A |    |

想转入下表。

|NN | XX | YY | ZZ | 
+---+----+----+----+
| A |  2 |  2 |  1 |
| B |  1 |  2 |  1 |
| C |  2 |  1 |  1 |

含义:列NN中的每个唯一值计数列XX,YY和ZZ中的NN值的数量

如何通过编写查询来完成?

2 个答案:

答案 0 :(得分:1)

这是一个相当丑陋的查询,但您的数据似乎并未正常化。我们可以加入一系列子查询,查找每列的字母数:

SELECT
    t.NN,
    xx.cnt_xx AS XX,
    yy.cnt_yy AS YY,
    zz.cnt_zz AS ZZ
FROM ( SELECT DISTINCT NN FROM yourTable ) t
LEFT JOIN ( SELECT XX, COUNT(*) AS cnt_xx FROM yourTable GROUP BY XX ) xx
    ON t.NN = xx.XX
LEFT JOIN ( SELECT YY, COUNT(*) AS cnt_yy FROM yourTable GROUP BY YY ) yy
    ON t.NN = yy.YY
LEFT JOIN ( SELECT ZZ, COUNT(*) AS cnt_zz FROM yourTable GROUP BY ZZ ) zz
    ON t.NN = zz.ZZ

enter image description here

Demo

答案 1 :(得分:1)

在mysql中,这有点困难。您可以使用:

select t.NN, 
(select count(XX) from `table` where XX = t.NN) as `XX`,
(select count(YY) from `table` where YY = t.NN) as `YY`,
(select count(ZZ) from `table` where ZZ = t.NN) as `ZZ`
from (select distinct NN from `table`) as t;