根据来自另一个的间隔更新表。 SQL Server

时间:2014-02-19 13:26:00

标签: sql sql-server

我需要计算每小时有多少男人在工作。我有两张桌子:

Hour     Men
------------
6        0
7        0
8        0
9        0
10       0
11       0
12       0

其中"Men"列是男性的数量。另一张表是:

ClockedInHour     ClockedOutHour
6                 10
7                 10
8                 12
6                 11
9                 12

因此,对于第二个表中的每个条目,我需要在"Men""ClockedInHour"之间的每小时增加第一个表中的"ClockedOutHour"列,包括表中的那些,如果没有光标就可以做到。

附加条件:它将成为表值函数的一部分。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

解决!

DECLARE @Hour6 INT
SET @Hour6 = (SELECT COUNT(*) FROM @table2 where ClockedOutHour >= 6 and ClockedInHour <= 6)
DECLARE @Hour7 INT
SET @Hour7 = (SELECT COUNT(*) FROM @table2 where ClockedOutHour >= 7 and ClockedInHour <= 7)
DECLARE @Hour8 INT
SET @Hour8 = (SELECT COUNT(*) FROM @table2 where ClockedOutHour >= 8 and ClockedInHour <= 8)
DECLARE @Hour9 INT
SET @Hour9 = (SELECT COUNT(*) FROM @table2 where ClockedOutHour >= 9 and ClockedInHour <= 9)
DECLARE @Hour10 INT
SET @Hour10 = (SELECT COUNT(*) FROM @table2 where ClockedOutHour >= 10 and ClockedInHour <= 10)
DECLARE @Hour11 INT
SET @Hour11 = (SELECT COUNT(*) FROM @table2 where ClockedOutHour >= 11 and ClockedInHour <= 11)
DECLARE @Hour12 INT
SET @Hour12 = (SELECT COUNT(*) FROM @tc where ClockedOutHour >= 12 and ClockedInHour <= 12)

UPDATE @table1 SET Man = @Hour6 WHERE Hour = 6
UPDATE @table1 SET Man = @Hour7 WHERE Hour = 7
UPDATE @table1 SET Man = @Hour8 WHERE Hour = 8
UPDATE @table1 SET Man = @Hour9 WHERE Hour = 9
UPDATE @table1 SET Man = @Hour10 WHERE Hour = 10
UPDATE @table1 SET Man = @Hour11 WHERE Hour = 11
UPDATE @table1 SET Man = @Hour12 WHERE Hour = 12

答案 1 :(得分:0)

您可以使用“插入触发器”执行此操作:

Go --terminate all preceding batch of statements

CREATE TRIGGER tg_MenCount ON dbo.table2 For INSERT
AS
SET XACT_ABORT, NOCOUNT ON
--Ignore zero row updates, inserts
IF NOT EXISTS (SELECT * FROM INSERTED) RETURN;

BEGIN TRY
    UPDATE T1
    set T1.men = T1.men +1
    FROM
       table1 T1
       INNER JOIN INSERTED I
       ON T1.hour between I.ClockedInHour and I.ClockedOutHour   
END TRY
BEGIN CATCH
   IF XACT_STATE() <> 0 ROLLBACK TRANSACTION
    --RAISERROR [rethrow caught error using @ErrorNumber, @ErrorMessage, etc]
END CATCH
GO