You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从关联的Articles与Attributes表中查询指定商品的指定属性

商品属性行转列结构化查询解决方案

数据表结构

Articles表(商品主表)

ArticleDescriptionCategory
A00001第一个商品X
A00002第二个商品X
A00003第三个商品Z

Attributes表(商品属性表)

ArticleAttributeValue
A00001Height1000
A00001Width2000
A00001Depth3000
A00002Height4000
A00002Width5000
A00002Depth6000

需求目标

筛选分类为X的商品,将指定属性(Height、Width)从行转换为列,得到如下结构化结果:

期望输出

ArticleDescriptionCategoryHeightWidth
A00001第一个商品X10002000
A00002第二个商品X40005000

实现方案

方案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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 05:25:58