Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Pivot + Counting

I need help with a SQL that will convert this table:

===================
| 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   |
===================

to this:

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

I can so simple counts, etc., but am struggling trying to pivot the table with the information derived. Any help is appreciated.

like image 819
StackOverflowNewbie Avatar asked Nov 21 '25 17:11

StackOverflowNewbie


1 Answers

Use:

  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
like image 137
OMG Ponies Avatar answered Nov 23 '25 05:11

OMG Ponies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!