sql-server - 从单个表中拆分列并作为多个列连接到另一个表中
问题描述
我想将一个表中的列拆分为另一个表中的多个列
假设我想将 FoodAttributeTable 加入 FoodTable:
美食桌
+------------+-------+
| Food | Price |
+------------+-------+
| Strawberry | 10 |
| Broccoli | 25 |
+------------+-------+
食物属性表
+------------+---------------+----------------+
| Food | AttributeName | AttributeValue |
+------------+---------------+----------------+
| Strawberry | Vitamin | C |
| Strawberry | Weight | 15g |
| Strawberry | Color | Red |
| Broccoli | Vitamin | B |
| Broccoli | Weight | 70g |
| Broccoli | Color | Green |
+------------+---------------+----------------+
表为:
美食桌
+------------+-------+---------+--------+-------+
| Food | Price | Vitamin | Weight | Color |
+------------+-------+---------+--------+-------+
| Strawberry | 10 | C | 15g | Red |
| Broccoli | 25 | B | 70g | Green |
+------------+-------+---------+--------+-------+
解决方案
您可以使用如下所示的简单 PIVOT 查询。查看PIVOT 上的官方 MSDN 文档。
select
Food,Price,Vitamin,Weight,Color
from
(
select f.Food,f.Price,
AttributeName ,AttributeValue
from
FoodTable f join
FoodAttributeTable fat on
f.Food=fat.Food
)s
pivot
(max(AttributeValue) for AttributeName in (Vitamin,Weight,Color))
p
这里还有一个live demo
推荐阅读
- c# - 如何处理 .NET Core 应用程序中的自定义错误
- java - 是否有 mongodb 查询来合并特定 mongodb 文档中的字段
- c# - ASPX 无法加载类型
- reactjs - 如何在无限滚动页面上保留/恢复滚动位置?
- python - jupyter notebook 中文件名的“CSV 文件不存在”
- sql - 我可以将一个查询的输出用作另一个选择子句中的列吗
- java - 为什么索引从 10 开始,即使我在 { for int i =0;}
- javascript - 如何使用代理访问类中的原始功能?
- javascript - 我想创建一个可以有多个列表项的水平导航栏
- amazon-s3 - 以可扩展的方式在多台机器上同步大量文件