我有两个如上所示的表格。我想创建一个选择语句,其结果如下:
基本上,我想加入“ Model”和“ Num”列,并引入“ Val”值,但基于“ Ver”将其分为两列。
SELECT 'a' as Model ,'1' as Num ,'v1' as Ver ,'9' as val INTO #RefTbl UNION ALL
SELECT 'a','2','v1','10' UNION ALL
SELECT 'a','3','v1','11' UNION ALL
SELECT 'a','1','v2','5' UNION ALL
SELECT 'a','2','v2','6' UNION ALL
SELECT 'a','3','v2','7' UNION ALL
SELECT 'b','1','v1','20' UNION ALL
SELECT 'b','1','v2','21' UNION ALL
SELECT 'b','2','v1','25' UNION ALL
SELECT 'b','2','v2','26'
SELECT '519' as ID,'a' as Model,'1' as Num INTO #OrderTbl UNION ALL
SELECT '5616','a','3' UNION ALL
SELECT '871','b','1'
-- failed attempt
SELECT o.*, '' as v1_val, '' as v2_val FROM #OrderTbl as o left join #RefTbl as r on o.Model = r.Model and o.Num = r.Num
答案 0 :(得分:3)
您可以加入并进行条件聚合:
select
d.ID,
d.Model,
d.Num,
max(case when r.Ver = 'val1' then Val end) V1_Val,
max(case when r.Ver = 'val2' then Val end) V2_Val
from DataTbl d
inner join ReferenceTbl r
on r.Model = d.Model
and r.Num = d.Num
group by
d.ID,
d.Model,
d.Num
或者,您可以加入两次-根据您的数据集,这可能会(或可能不会)表现更好:
select
d.ID,
d.Model,
d.Num,
r1.Val V1_Val,
r2.Val V2_Val
from DataTbl d
left join ReferenceTbl r1
on r1.Model = d.Model
and r1.Num = d.Num
and r1.Ver = 'val1'
left join ReferenceTbl r2
on r2.Model = d.Model
and r2.Num = d.Num
and r2.Ver = 'val2'
答案 1 :(得分:1)
Case + Group by可在大多数数据库系统上使用,这很好。
使用SQL Server PIVOT的替代答案(供参考)
WITH RefTbl AS (
SELECT 'a' as Model ,'1' as Num ,'v1' as Ver ,'9' as val UNION ALL
SELECT 'a','2','v1','10' UNION ALL
SELECT 'a','3','v1','11' UNION ALL
SELECT 'a','1','v2','5' UNION ALL
SELECT 'a','2','v2','6' UNION ALL
SELECT 'a','3','v2','7' UNION ALL
SELECT 'b','1','v1','20' UNION ALL
SELECT 'b','1','v2','21' UNION ALL
SELECT 'b','2','v1','25' UNION ALL
SELECT 'b','2','v2','26'),
OrderTbl AS (
SELECT '519' as ID,'a' as Model,'1' as Num UNION ALL
SELECT '5616','a','3' UNION ALL
SELECT '871','b','1'
)
SELECT Id, Model, Num AS Model, [v1] AS v1_Val, [v2] as v2_Val
FROM
(SELECT o.id, r.Model, r.Num, r.val, r.ver from OrderTbl as o
left join RefTbl as r on o.Model = r.Model and o.Num = r.Num) AS SourceTable
PIVOT
(MAX(val) FOR ver IN ([v1], [v2])) AS PivotTable;
Id Model Model v1_Val v2_Val
519 a 1 9 5
5616 a 3 11 7
871 b 1 20 21