我的表格中包含Leave
种类型Annual
,Casual
,Medical
等。
现在我需要根据离开类型Annual Leave
,Casual Leave
,Medical Leave
等将其拆分为多个列。
表LeaveAccount
LeaveAccountID,
LeaveTypeID,
EmployeeID,
AccountingYearID,
TotalLeaves,
LeavesTaken
表LeaveType
LeaveTypeID,
LeaveTypeName
我的查询[给出一个无限循环]是:
[FullName,EmplyeeID,AnnualLeave,ShortLeave,Medical Leave]
SELECT
e.FullName
, e.EmployeeId
, a.TotalLeaves as AnnualLeave
, b.TotalLeaves as shortleave
, c.TotalLeaves as MedicalLeave
FROM
LeaveAccount a
, Employee e
, LeaveAccount b
, LeaveAccount c
WHERE
(a.EmployeeId = b.EmployeeId)
and (
(a.LeaveTypeId = 0)
and (b.LeaveTypeId = 20)
and (c.LeaveTypeId = 1)
)
我是否需要使用动态SQL?怎么能分开我喜欢这个?
答案 0 :(得分:0)
为什么需要拆分你的桌子?
当您可以创建表格的VIEWS时,每个视图将包含一列:
CREATE VIEW
Annual_Leave
AS
SELECT
Annual
FROM
Leave types;
您对其余列执行相同操作。
答案 1 :(得分:0)
尝试使用SubSelects:
SELECT
e.FullName
, e.EmployeeId
, (SELECT SUM(a.TotalLeaves) FROM LeaveAccount a WHERE a.EmployeeId = e.EmployeeId AND a.LeaveTypeId = 0) AS "AnnualLeave"
, (SELECT SUM(b.TotalLeaves) FROM LeaveAccount b WHERE b.EmployeeId = e.EmployeeId AND b.LeaveTypeId = 20) AS "ShortLeave"
, (SELECT SUM(c.TotalLeaves) FROM LeaveAccount c WHERE c.EmployeeId = e.EmployeeId AND c.LeaveTypeId = 1) AS "MedicalLeave"
FROM
Employee e
另一种解决方案是分组:
SELECT
e.FullName
, e.EmployeeId
, SUM(a.TotalLeaves) AS "AnnualLeave"
, SUM(b.TotalLeaves) AS "ShortLeave"
, SUM(c.TotalLeaves) AS "MedicalLeave"
FROM
Employee e
INNER JOIN
LeaveAccount a
ON
a.EmployeeId = e.EmployeeId
AND a.LeaveTypeId = 0
INNER JOIN
LeaveAccount b
ON
b.EmployeeId = e.EmployeeId
AND b.LeaveTypeId = 20
INNER JOIN
LeaveAccount c
ON
c.EmployeeId = e.EmployeeId
AND c.LeaveTypeId = 1
GROUP BY
e.FullName
, e.EmployeeId
修改:根据您的数据,您可能必须使用LEFT OUTER JOIN
代替INNER JOIN
。