如何从关联的Articles与Attributes表中查询指定商品的指定属性
商品属性行转列结构化查询解决方案
数据表结构
Articles表(商品主表)
| Article | Description | Category |
|---|---|---|
| A00001 | 第一个商品 | X |
| A00002 | 第二个商品 | X |
| A00003 | 第三个商品 | Z |
Attributes表(商品属性表)
| Article | Attribute | Value |
|---|---|---|
| A00001 | Height | 1000 |
| A00001 | Width | 2000 |
| A00001 | Depth | 3000 |
| A00002 | Height | 4000 |
| A00002 | Width | 5000 |
| A00002 | Depth | 6000 |
需求目标
筛选分类为X的商品,将指定属性(Height、Width)从行转换为列,得到如下结构化结果:
期望输出
| Article | Description | Category | Height | Width |
|---|---|---|---|---|
| A00001 | 第一个商品 | X | 1000 | 2000 |
| A00002 | 第二个商品 | X | 4000 | 5000 |
实现方案
方案1:条件聚合(通用SQL,兼容所有主流数据库)
使用CASE WHEN结合聚合函数实现行转列,兼容性最强:
SELECT a.Article, a.Description, a.Category, MAX(CASE WHEN att.Attribute = 'Height' THEN att.Value END) AS Height, MAX(CASE WHEN att.Attribute = 'Width' THEN att.Value END) AS Width FROM Articles a LEFT JOIN Attributes att ON a.Article = att.Article WHERE a.Category = 'X' GROUP BY a.Article, a.Description, a.Category;
方案2:PIVOT语法(适用于SQL Server、Oracle等支持该语法的数据库)
如果数据库支持PIVOT,可以用更简洁的写法:
SELECT Article, Description, Category, Height, Width FROM ( SELECT a.Article, a.Description, a.Category, att.Attribute, att.Value FROM Articles a LEFT JOIN Attributes att ON a.Article = att.Article WHERE a.Category = 'X' ) AS SourceData PIVOT ( MAX(Value) FOR Attribute IN (Height, Width) ) AS PivotResult;
补充说明
- 若需新增属性列(如Depth),只需在SELECT语句中添加对应的
MAX(CASE...),或在PIVOT的IN子句中加入属性名; - 使用
LEFT JOIN可确保无对应属性的商品仍能出现在结果中,属性值显示为NULL; - 条件聚合写法不依赖数据库特定语法,可在MySQL、PostgreSQL、SQL Server等环境通用。
内容的提问来源于stack exchange,提问作者user24663749
相关产品推荐
相关产品推荐

