我有两张桌子。我想把结果放到一行,但是当我尝试使用下面的查询时,它会导致重复。
查询:
Select OrgaID, UnitID, LeaveTitle, NoOfFromService, NoOfToService,
EmpType.EmployeeTypeName, IsExpatriate,
(ALR.LeaveTypeShortName + '(' + convert(varchar,ALR.NoofDays) + ') | ' +
MLR.LeaveTypeShortName + '(' + convert(varchar,MLR.NoofDays) + ') | ')
Leaves
From LeaveCategory LvCat
Left Join (Select LeaveCategoryID, LeaveTypeShortName, NoofDays From
LeaveEntitledEntry Where LeaveTypeShortName = 'AL' ) ALR On
ALR.LeaveCategoryId = LvCat.Id
Left Join (Select LeaveCategoryID, LeaveTypeShortName, NoofDays From
LeaveEntitledEntry Where LeaveTypeShortName = 'MDL' ) MLR On
ALR.LeaveCategoryId = LvCat.Id
Where OrgaID = @OrgaID and LvCat.Status = 1
供参考:
表2 :( LeaveEntitledEntry)
结果:
那么我怎样才能改变我的联接以达到预期的效果。任何帮助赞赏。提前致谢
答案 0 :(得分:1)
您可以尝试使用条件聚合通过使用连接到单个子查询来访问两种类型的休假数据。这个技巧可能起作用的原因是允许我们为每个LeaveCategoryID
生成一条记录,以及NoofDays
和AL
类型的MDL
值。这意味着我们可以只使用一个连接,这可以避免您遇到的重复问题。
WITH cte AS (
SELECT
LeaveCategoryID,
MAX(CASE WHEN LeaveTypeShortName = 'AL' THEN NoofDays END) AS NoofDaysAL,
MAX(CASE WHEN LeaveTypeShortName = 'MDL' THEN NoofDays END) AS NoofDaysMDL
FROM LeaveEntitledEntry
GROUP BY LeaveCategoryID
)
SELECT
OrgaID,
UnitID,
LeaveTitle,
NoOfFromService,
NoOfToService,
EmpType.EmployeeTypeName,
IsExpatriate,
'AL(' + CONVERT(varchar, t.NoofDaysAL) + ') | ' +
'MDL(' + CONVERT(varchar, t. NoofDaysMDL) + ') | ') AS Leaves
FROM LeaveCategory LvCat
LEFT JOIN cte t
ON LvCat.Id = t.LeaveCategoryID
WHERE
OrgaID = @OrgaID AND
LvCat.Status = 1;