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

SQL Server:如何将不同Product_Tag的查询结果合并为同表多列?

SQL Server 结果合并解决方案

针对你需要将Product_Tag为PIT-10和PIT-11的查询结果合并为四列输出的需求,提供两种可行方案:

方案一:条件聚合(行转列)

通过CASE WHEN结合聚合函数,将同一存放地点的不同仪器数据合并到同一行,写法简洁高效:

SELECT
    Product_Mark AS PIT_10_Product_Mark,
    MAX(CASE WHEN Product_Tag = 'PIT-10' THEN Product_Model END) AS PIT_10_Product_Model,
    Product_Mark AS PIT_11_Product_Mark,
    MAX(CASE WHEN Product_Tag = 'PIT-11' THEN Product_Model END) AS PIT_11_Product_Model
FROM Product_2
WHERE Product_Tag IN ('PIT-10', 'PIT-11')
GROUP BY Product_Mark

说明:MAX函数用于取出对应标签的唯一仪器型号(每个地点对应单条PIT-10/PIT-11记录),若某地点缺少其中一个标签的仪器,对应列会显示NULL。

方案二:正确的自连接

如果之前LEFT JOIN失败,大概率是连接条件未匹配存放地点+标签筛选,调整后的自连接写法如下:

SELECT
    t1.Product_Mark AS PIT_10_Product_Mark,
    t1.Product_Model AS PIT_10_Product_Model,
    t2.Product_Mark AS PIT_11_Product_Mark,
    t2.Product_Model AS PIT_11_Product_Model
FROM Product_2 t1
LEFT JOIN Product_2 t2
    ON t1.Product_Mark = t2.Product_Mark
    AND t2.Product_Tag = 'PIT-11'
WHERE t1.Product_Tag = 'PIT-10'

若需要包含仅存在PIT-11的地点记录,可改为FULL JOIN并调整筛选条件:

SELECT
    t1.Product_Mark AS PIT_10_Product_Mark,
    t1.Product_Model AS PIT_10_Product_Model,
    t2.Product_Mark AS PIT_11_Product_Mark,
    t2.Product_Model AS PIT_11_Product_Model
FROM Product_2 t1
FULL JOIN Product_2 t2
    ON t1.Product_Mark = t2.Product_Mark
WHERE (t1.Product_Tag = 'PIT-10' OR t2.Product_Tag = 'PIT-11')

内容的提问来源于stack exchange,提问作者Alberto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:10:25