多个CASE WHEN时插入选择

时间:2016-11-30 12:44:45

标签: sql-server insert case

我正在尝试使用具有多个案例场景的另一个表中的select插入到表中。每个人都有多个值,这会在连接表中提供多行。我想根据连接表中的col1选择col2。

到目前为止,结果是3行同一个人,每行3个值中的1个。

见结果

enter image description here

INSERT INTO #temp (Name, WageNo, Tiltraedelses_dato, Jubilaeum ,Sabbatical, Anciennitet)

SELECT 
 e.FirstName, 
 e.WageSystemKey, 
 e.[StartDate],
CASE WHEN v.EmployeeCustomColumnId = 2 THEN v.Value END,
CASE WHEN v.EmployeeCustomColumnId = 3 THEN v.Value END,
CASE WHEN v.EmployeeCustomColumnId = 1 THEN v.Value END

FROM Employees e
LEFT JOIN EmployeeCustomValue v on e.EmployeeId = v.EmployeeId

SELECT * FROM #temp

2 个答案:

答案 0 :(得分:1)

我认为你需要一个带有条件聚合的小组,类似这样的

RIGHT JOIN 
    (Select Fields From [WarehouseMgmt].[DimProductType] Where Field = "What you want") PT 
    ON PT.Id = DP.FirstDepositProductTypeId

答案 1 :(得分:0)

以下是其他几种方法。

INSERT INTO #temp (Name, WageNo, Tiltraedelses_dato, Jubilaeum ,Sabbatical, Anciennitet)

SELECT 
e.FirstName, 
e.WageSystemKey, 
e.[StartDate],
v2.Value,
v3.Value,
v1.Value

FROM Employees e
LEFT JOIN EmployeeCustomValue v1 on e.EmployeeId = v1.EmployeeId and v1.EmployeeCustomColumnId = 1
LEFT JOIN EmployeeCustomValue v2 on e.EmployeeId = v2.EmployeeId and v2.EmployeeCustomColumnId = 2
LEFT JOIN EmployeeCustomValue v3 on e.EmployeeId = v3.EmployeeId and v3.EmployeeCustomColumnId = 3

或者

INSERT INTO #temp (Name, WageNo, Tiltraedelses_dato, Jubilaeum ,Sabbatical, Anciennitet)

SELECT FirstName, WageSystemKey, [StartDate], 
MAX(Jubilaeum) AS Jubilaeum, MAX(Sabbatical) AS Sabbatical, 
MAX(Anciennitet) AS Anciennitet
FROM (SELECT 
e.FirstName, 
e.WageSystemKey, 
e.[StartDate],
CASE WHEN v.EmployeeCustomColumnId = 2 THEN v.Value END AS Jubilaeum,
CASE WHEN v.EmployeeCustomColumnId = 3 THEN v.Value END AS Sabbatical,
CASE WHEN v.EmployeeCustomColumnId = 1 THEN v.Value END AS Anciennitet

FROM Employees e
LEFT JOIN EmployeeCustomValue v on e.EmployeeId = v.EmployeeId) AA
GROUP BY FirstName, WageSystemKey, [StartDate]