我會做的方式是computed column
和user defined function
的組合。
該函數允許彙總數據。在一個計算列中,你只能使用同一行的字段,因此調用一個函數(這是允許的)是必要的。
計算列允許它連續工作,不需要任何附加查詢或臨時表等。設置後,您不需要運行夜間更新或觸發器或任何類型的數據以更新數據,包括何時記錄更改或被刪除。
這裏是我的解決方案...和SqlFiddle:http://www.sqlfiddle.com/#!3/cd8d6/1/0
編輯: 我已經更新這反映您需要每名員工計算運行總計。 SqlFiddle也更新了。
功能:
Create Function udf_GetRunningTotals (
@CheckDate DateTime,
@EmployeeID int
)
Returns Decimal(18,2)
As
Begin
Declare @Result Decimal(18,2)
Select @Result = Cast(Sum(rt.Hrs) As Decimal(18,2))
From RunningTotals rt
Where rt.CheckDate <= @CheckDate
And Year(rt.CheckDate) = Year(@CheckDate)
And rt.EmployeeID = @EmployeeID
Return @Result
End
表模式:
Create Table [dbo].[RunningTotals](
[ID] [int] Identity(1,1) NOT NULL,
[EmployeeID] [int] NOT NULL,
[CheckDate] [datetime] NOT NULL,
[CheckNumber] [int] NOT NULL,
[Hrs] [decimal](18, 2) NOT NULL,
[Hrs_Ytd] AS ([dbo].[udf_GetRunningTotals]([CheckDate],[EmployeeID])), -- must add after table creation and function creation due to inter-referencing of table and function
Constraint [PK_RunningTotals3] Primary Key Clustered (
[ID] ASC
) With (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
)
) On [PRIMARY]
結果會從中總結出YTD小時,每一年。
注 -
因爲是因爲它們相互引用您不能創建函數或表。 首先,創建除了計算列以外的所有表格; 然後,創建該功能。 最後,修改表格並添加計算列。
這裏是一個完整的運行測試腳本:
-- Table schema
Create Table [dbo].[RunningTotals](
[ID] [int] Identity(1,1) NOT NULL,
[EmployeeID] [int] NOT NULL,
[CheckDate] [datetime] NOT NULL,
[CheckNumber] [int] NOT NULL,
[Hrs] [decimal](18, 2) NOT NULL,
Constraint [PK_RunningTotals3] Primary Key Clustered (
[ID] ASC
) With (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
)
) On [PRIMARY]
Go
-- UDF Function to compute totals
Create Function udf_GetRunningTotals (
@CheckDate DateTime,
@EmployeeID int
)
Returns Decimal(18,2)
As
Begin
Declare @Result Decimal(18,2)
Select @Result = Cast(Sum(rt.Hrs) As Decimal(18,2))
From RunningTotals rt
Where rt.CheckDate <= @CheckDate
And Year(rt.CheckDate) = Year(@CheckDate)
And rt.EmployeeID = @EmployeeID
Return @Result
End
Go
-- Add the computed column to the table
Alter Table RunningTotals Add [Hrs_Ytd] As (dbo.udf_GetRunningTotals(CheckDate, EmployeeID))
Go
-- Insert some test data
Insert into RunningTotals Values (334944, '1/1/2014', '1001', 40.00)
Insert into RunningTotals Values (334944, '1/5/2014', '1002', 30.00)
Insert into RunningTotals Values (334944, '1/15/2014', '1003', 32.50)
Insert into RunningTotals Values (334945, '1/5/2014', '1001', 10.00)
Insert into RunningTotals Values (334945, '1/6/2014', '1002', 20.00)
Insert into RunningTotals Values (334945, '1/8/2014', '1003', 12.50)
-- Test the computed column
Select * From RunningTotals
+1這很有效。感謝您的幫助和鏈接。 – HKImpact