SQL 将选择查询添加到另一个选择查询作为新列

问题描述 投票:0回答:1

我有两个 SQL 选择查询。我想将第二个选择结果作为新列添加到第一个查询中。我该怎么办?

我的查询 - 第一个查询:

SELECT 
    [Value], ColumnIndex, RowIndex + 1 AS RowIndex,
    Axis, SegmentationModuleType, ModuleType, VersionId, IsTotalValue FROM 
    FinalWeightCalculation
WHERE 
    Axis IS NULL
    AND IsTotalValue = 1 
    AND SegmentationModuleType = 'Choosing' 
    AND ModuleType = 'TSY02' 
    AND VersionId = 299 
    AND AccountGuid = 'f069b6d7-b2d1-4f36-b6a4-9d830f35de73' 
ORDER BY
    RowIndex

第二个查询:

select ROW_NUMBER() OVER (ORDER BY OrderNo) as RowIndex, Name from Criteria where VersionId = 299 order by OrderNo

Image

sql join combine
1个回答
0
投票

您可以加入行号:

WITH cte1 AS (
    -- your first query
),
cte2 AS (
    SELECT Name, ROW_NUMBER() OVER (ORDER BY OrderNo) rn
    FROM Criteria 
    WHERE VersionId = 299 
)

SELECT t1.*, t2.Name
FROM cte1 t1
LEFT JOIN cte2 t2
    ON t2.rn = t1.RowIndex
ORDER BY t1.RowIndex;
© www.soinside.com 2019 - 2024. All rights reserved.