gpt4 book ai didi

sql - MySQL:数据透视+计数

转载 作者:可可西里 更新时间:2023-11-01 07:57:35 28 4
gpt4 key购买 nike

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

关于sql - MySQL:数据透视+计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3561881/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com