mysql - 将具有重复值的行转换为列 - MySQL
问题描述
我有一个表“A”,看起来像:
_______________________________________________________________
|query_id | query | response |user_response_count |
|---------------------------------------------------------------
| 1 | acne | BothBad | 2 |
| 1 | acne | BothGood | 1 |
| 2 | asthma | BothBad | 1 |
| 2 | asthma | product 1 | 1 |
| 2 | asthma | BothGood | 1 |
| 3 | bell palsy | product 2 | 2 |
| 3 | bell palsy | BothGood | 1 |
---------------------------------------------------------------
我想编写一个查询来获得如下所示的内容:
__________________________________________________________________________________
| query_id | query | BothGood | BothBad | Product 1 | Product 2 |
-----------------------------------------------------------------------------------
| 1 | acne | 1 | 2 | 0 | 0 |
| 2 | asthma | 1 | 1 | 1 | 0 |
| 3 | bell palsy| 1 | 0 | 0 | 2 |
-----------------------------------------------------------------------------------
“user_response_count”列实际上是说,2 个用户为“acne”查询选择了“BothBad”选项。
我知道,通过使用max
,我可以将行更改为列,但在这里很难做到最大。有什么想法吗?
解决方案
条件聚合:
select query_id, query,
sum(case when response = 'BothGood' then cnt else 0 end) as BothGood,
sum(case when response = 'BothBad' then cnt else 0 end) as BothBad,
sum(case when response = 'product 1' then cnt else 0 end) as product1,
sum(case when response = 'product 2' then cnt else 0 end) as product2
from a
group by query_id, query;
推荐阅读
- sql - 将一个表中的记录插入到另一个表中,递增 id
- angular - 如何将 Angular 配置为在开发模式下服务,但使用选定的生产环境变量?
- android - 是否可以将 adb 命令批量设置为变量?
- azure - Azure Functions BlobTrigger blobPath 嵌套配置绑定
- java - AtomicReference compareAndSet:字符串引用与值相等
- tableau-api - 将 Tableau 数据导出为 CSV
- kubernetes - 限制对服务帐户的访问
- c# - .NET Core 3 / EF.Core 3:`QueryModelGenerator`、`RelationalQueryModelVisitor` 等发生了什么
- go - 使用 Go 的 base64.StdEncoding.Decode() 方法:如何选择目标字节片的大小?
- java - 抛出异常时无法捕获异常