MySQL:数据透视计数

我需要有关将转换此表的SQL的帮助:

===================
| Id | FK | Status|
===================
| 1  | A  | 100   |
| 2  | A  | 101   |
| 3  | B  | 100   |
| 4  | B  | 101   |
| 5  | C  | 100   |
| 6  | C  | 101   |
| 7  | A  | 102   |
| 8  | A  | 102   |
| 9  | B  | 102   |
| 10 | B  | 102   |
===================

对此:

==========================================
| FK | Count 100 | Count 101 | Count 102 |
==========================================
| A  | 1         | 1         | 2         |
| B  | 1         | 1         | 2         |
| C  | 1         | 1         | 0         |
==========================================

我可以这么简单,等等,但我正在努力尝试使用派生的信息来转动表格.任何帮助表示赞赏.

解决方法:

使用:

  SELECT t.fk,
         SUM(CASE WHEN t.status = 100 THEN 1 ELSE 0 END) AS count_100,
         SUM(CASE WHEN t.status = 101 THEN 1 ELSE 0 END) AS count_101,
         SUM(CASE WHEN t.status = 102 THEN 1 ELSE 0 END) AS count_102
    FROM TABLE t
GROUP BY t.fk
上一篇:php – MYSQL – 从不同的行中获取值并将它们返回到同一行


下一篇:mysql – 在列中获取表行