sql - SQL:将宽表转换为窄表
问题描述
我有一个表,其中每一行都有一些布尔字段,如下所示:
user_id | USD | EUR | CAD | ....
1 | 1 | 1 | 0 | ....
2 | 0 | 1 | 1 | ....
我需要把它转换成这样的东西:
user_id | currency
1 | USD
1 | EUR
2 | EUR
2 | CAD
我设法用大量的 UNION(每种货币一个)构建了一个丑陋的 SQL,但我觉得这不是最好的方法。帮助任何人?
PS 此查询将在 AWS Athena 上执行,因此我担心成本,我希望对此进行最优化的查询。
解决方案
如果您的数据库支持横向连接和values()
行构造函数,那么您可以执行以下操作:
select x.user_id, x.currency
from mytable t
cross join lateral (values(user_id, 'USD', usd), (user_id, 'EUR', eur), (user_id, 'CAD', cad)) x(user_id, currency, val)
where x.val= 1
cross apply
一些数据库使用而不是实现横向连接cross join lateral
。
一种更便携的方法是union all
. 这效率较低,因为它需要多次表扫描:
select user_id, 'USD'currency from mytable where usd = 1
union all select user_id, 'EUR' from mytable where eur = 1
union all select user_id, 'CAD' from mytable where cad = 1
推荐阅读
- flutter - Flutter 设置一周中的特定日期通知
- javascript - nginx反向代理后面的create-react-app代码更改未在浏览器中重新加载
- powershell - 从列表 Powershell 中获取距今天最近的日期
- java - 为什么这个 Java 程序不能编译?
- magnolia - 营销标签未在 Magnolia 页面中呈现内容
- javascript - 如何阻止此单击事件与前一个事件同时发生?Javascript纸牌游戏
- php - 错误问题:1215 无法添加外键约束
- c# - 对具有相同条件的数据表值求和
- docker - 使用 Google Cloud 代码在 vscode 中指定本地 docker 容器注册表
- excel - 让所有黄色单元格在范围内的快速方法