MySQL:Pivot + Counting

时间:2010-08-24 23:45:48

标签: sql mysql database pivot aggregate-functions

我需要有关将转换此表的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         |
==========================================

我可以如此简单地计算等等,但我正在努力尝试使用派生的信息来转动表格。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:6)

使用:

  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

答案 1 :(得分:0)

使用:

select * from 
(select fk,fk  as fk1,statusFK from #t
) as t
pivot
(COUNT(fk1) for statusFK IN ([100],[101],[102])
) AS pt