SQL Server:联接表和插入新数据时重复行?

时间:2018-12-13 10:36:48

标签: sql sql-server group-by duplicates left-join

我有两个表,一个表记录每个EmployeeIDtbl.HolidayRequest)请求的假期:

EmployeeID  | HoursRequested |  
------------+----------------+
1           | 8              |     
2           | 16             |     
3           | 8              | 
2           | 8              |
1           | 16             |

第二张表记录了由以下查询创建的每位员工(tbl.HoursRequestedPerEmployee)要求的总时数:

INSERT INTO [dbo].[HoursTakenPerEmployee]
    SELECT
        [dbo].[LotusEmployees].[EmployeeNo.], 
        SUM(ISNULL([dbo].[HolidayRequestForm].[HoursRequested], 0)) AS HoursTaken
    FROM
        [dbo].[LotusEmployees]
    LEFT JOIN
        [dbo].[HolidayRequestForm] ON [dbo].[LotusEmployees].[EmployeeNo.] = [dbo].[HolidayRequestForm].EmployeeNo.]
    GROUP BY
        [dbo].[LotusEmployees].[EmployeeNo.] 

结果:

EmployeeID  | Total HoursRequested |  
------------+----------------------+
1           |       24             |     
2           |       24             |     
3           |        8             |      
1           |       24             |      
2           |       24             |
3           |        8             |

在将新条目插入tbl.HoursRequestedPerEmployee并且没有重复项时,如何更新表tbl.HolidayRequest

1 个答案:

答案 0 :(得分:0)

只需使用一个视图:

CREATE VIEW vw_HoursTakenPerEmployee AS
    SELECT le.[EmployeeNo.], 
           COALESCE(SUM(hrf.[HoursRequested]), 0) AS HoursTaken
    FROM [dbo].[LotusEmployees] le LEFT JOIN
         [dbo].[HolidayRequestForm] hrf
          ON le.[EmployeeNo.] = hrf.EmployeeNo.]
    GROUP BYle.[EmployeeNo.];

该视图将在您需要时重新计算信息。

如果您认为需要将信息存储在表中(例如出于性能原因),则可以使用触发器来使表保持最新状态(这太麻烦了!)。或截断并重​​新创建表:

TRUNCATE TABLE [dbo].[HoursTakenPerEmployee];

INSERT INTO [dbo].[HoursTakenPerEmployee] . . .