我正在對存在于許多遠程站點的一些舊 SQL 表進行合理化,因此我需要構建一個查詢,以便從壞的舊表中生成新的好表。所以為此,我們有table1哪些列DataGroup和Case1as nvarchar,但這些是應用程式中的列舉,所以我創建了新表來存盤列舉,但我需要獲取 ID。不幸的是,我們需要將該表的所有列舉存盤在一個表中,因此該表ExData包含 4 列:id、name和。ExGroupIdDataGroupId
與文本一樣DataGroup,table1我們也需要從 kvp 表中查找 int idDataGroupTable
這是我到目前為止的查詢:
SELECT
<Other Columns>,
t1.ExDataId AS Case1
FROM
table1
LEFT JOIN (
SELECT
DataGroupTable.name AS dataGroup,
ExData.id AS ExDataId,
ExData.name AS ExDataName,
ExGroup.name AS ExGroupName
FROM
ExData
LEFT JOIN DataGroupTable ON DataGroupTable.id = ExData.dataGroupId
LEFT JOIN ExGroup ON ExGroup.id = ExData.ExGroupId
) t1 ON t1.dataGroup = table1.DataGroup
AND t1.ExGroupName = 'case1'
AND t1.ExDataName = table1.Case1
GO
...但是,雖然這可以檢索 Case1,但我將如何獲取 Case2?我有 7 個案例要處理,雖然我可以通過自由復制粘貼來解決這個問題,但這遠非優雅。
此外,這一切都進入一個 INSERT 陳述句,所以理想情況下這應該回傳 Case1、Case2 等作為 ExDataId 的
請幫忙。
根據要求提供示例資料,所有 id 將從 0 開始,但為了清楚起見,我將以下所有內容都設為唯一。
表格1:
DataGroup Case1 Case2 Case3 <Other Columns>
ABCD bob bob chris 1
ABCD pete gary chris 2
EFGH bob mike rod 3
資料組表:
id name
11 ABCD
12 EFGH
防爆集團:
id name
21 case1
22 case2
23 case3
資料:
id name ExGroupId dataGroupId
31 bob 21 11
32 pete 21 11
33 bob 21 12
34 bob 22 11
35 gary 22 11
36 mike 22 12
37 chris 23 11
38 rod 23 12
理想結果:
<Other Columns> Case1 Case2 Case3
1 31 34 37
2 32 35 38
3 33 36 38
uj5u.com熱心網友回復:
公用表運算式怎么樣?
WITH ExDataCTE AS (
SELECT
DataGroupTable.name AS dataGroup,
ExData.id AS ExDataId,
ExData.name AS ExDataName,
ExGroup.name AS ExGroupName
FROM
ExData
LEFT JOIN DataGroupTable ON DataGroupTable.id = ExData.dataGroupId
LEFT JOIN ExGroup ON ExGroup.id = ExData.ExGroupId)
SELECT
<Other Columns>,
t1.ExDataId AS Case1,
t2.ExDataId AS Case2,
t3.ExDataId AS Case3
FROM
table1
LEFT JOIN ExDataCTE t1 ON (t1.dataGroup = table1.DataGroup
AND t1.ExGroupName = 'case1'
AND t1.ExDataName = table1.Case1)
LEFT JOIN ExDataCTE t2 ON (t2.dataGroup = table1.DataGroup
AND t2.ExGroupName = 'case2'
AND t2.ExDataName = table1.Case2)
LEFT JOIN ExDataCTE t3 ON (t3.dataGroup = table1.DataGroup
AND t3.ExGroupName = 'case3'
AND t3.ExDataName = table1.Case3)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/456560.html
下一篇:每次遞回將SQL遞回限制為單行
