|
与以前几乎相同的数据结构在于 EmOvertime中 另一个名字叫 AttdDate”的 列, 用于指示员工的出勤日期。EmOvertime 表中数据的示例。# T, W% {/ k' C0 J7 [" G$ c
Table Name : EmOvertimeEmpId AttdDate TotalOtReal 20166年 201662016-05-09 2.00 20166年 201662016-05-10 2.00 20166年 201662016-05-11 2.00 20166年 201662016-05-12 2.000 3 20166年 2016-05-12 3.00来自 CsOrganization 和 EmHisOrganization
" E* S2 s' ` ^: c& y P L数据与上一个问题相同。假设我想在2016年5月12日展示它TotalHours查询值的所有组织数据将如下:
$ P4 Z/ W$ S) \9 a+ L( X- T- pWITHCTE_OrgHoursAS(SELECT Org.OrgId ,Org.OrgParentId ,Org.OrgName ,ISNULL(Overtime.TotalOtReal,0) AS SumHours ,Overtime.AttdDateFROM CsOrganization AS Org LEFT JOIN EmHisOrganization AS Emp ON Emp.OrgId = Org.OrgID LEFT JOIN EmOvertime AS Overtime ON Overtime.EmpId = Emp.EmpIdGROUP BY Org.OrgId ,Org.OrgParentId ,Org.OrgName ,Overtime.TotalOtReal ,Overtime.AttdDate),CTE_RecursiveAS(SELECT CTE_OrgHours.OrgId ,CTE_OrgHours.OrgParentId ,CTE_OrgHours.OrgName ,CTE_OrgHours.SumHours ,CTE_OrgHours.AttdDate ,1 AS Lvl ,CTE_OrgHours.OrgId AS StartOrgId ,CTE_OrgHours.OrgName AS StartOrgNameFROM CTE_OrgHoursUNION ALLSELECT CTE_OrgHours.OrgId ,CTE_OrgHours.OrgParentId ,CTE_OrgHours.OrgName ,CTE_OrgHours.SumHours ,CTE_OrgHours.AttdDate ,CTE_Recursive.Lvl 1 AS Lvl ,CTE_Recursive.StartOrgId ,CTE_Recursive.StartOrgNameFROM CTE_OrgHours INNER JOIN CTE_Recursive ON CTE_Recursive.OrgId = CTE_OrgHours.OrgParentId)SELECT StartOrgId ,StartOrgName ,SUM(SumHours) AS TotalHoursFROM CTE_RecursiveWHERE AttdDate = '2016-05-12'GROUP BY StartOrgId ,StartOrgNameORDER BY StartOrgId但查询结果如下: @# w9 _0 v$ @1 ~. i0 X' s2 L& q* B
OrgId OrgName TotalHours X COMPANY 14.002 Administrator 14.003 Adm 122.000 4 Adm 2 .005 Adm 1_1 0.00虽然应该是正确的:- B6 D1 D' [$ F( ?$ k
Desired OutputOrgId OrgName TotalHours X COMPANY 5.002 Administrator 5.003 Adm 1 333 33333.000 4 Adm 2 .005 Adm 1_1 0.00似乎在 EmOvertime 以儿童数据为父亲数据的数量 循环,它有四个相同的ID。因此,将显示值12.00.如何解决这个问题?
/ d3 ^, K& ?2 j- o9 l- x感谢任何帮助。; m, A9 n5 X1 G2 X% k
' k5 }/ h+ B7 p* ^4 K' v, {7 _
解决方案: |
|