基于另外两个表更新表

时间:2014-11-30 04:47:04

标签: sql sql-server-2008 merge sql-update

我有3个表Customer,customerCategory,出勤如下图所示:

客户:

CustomerId | CustomerCategory | Name

A1         | 2                | User1
B1         | 1                | User2
C1         | 3                | User3

CustomerCategory

CustCategoryId | CategoryName | StartTime | EndTime
1              | Category1    | 8:15      | 17:15
2              | Category2    | 7.30      | 17:30
3              | Category3    | 8.15      | 15:15

考勤

Id | CustomerId | InTime | OutTime
1  | A1         | 7:30   | 17:30
2  | A1         | 7:30   | NULL
3  | B1         | 8.15   | NULL
4  | C1         | 8:10   | NULL

我想将Attendance Table Outtime列更新为来自CustomerCategory表的相关Endtime,其中Attendane.Outime为NULL。我希望我能写一个合并查询,但我很困惑。有没有其他方法可以更新Attenance表来设置相关的OutTime?

2 个答案:

答案 0 :(得分:2)

UPDATE Attendance
SET Attendance.OutTime = CustomerCategory.EndTime
FROM Attendance
INNER JOIN Customer
ON (Attendance.CustomerID = Customer.CustomerID)
INNER JOIN CustomerCategory
ON (Customer.CustomerCategory = CustomerCategory.CustCategoryId)
WHERE Attendance.OutTime IS NULL;

您可能需要稍微使用语法,因为我暂时没有处理MS SQL,但基本思路如上所述。如果您有任何困难,请告诉我。

答案 1 :(得分:1)

使用Merge尝试以下内容:

Declare @Customer table (CustomerId varchar(5), CustomerCategory int, Name varchar(10))

insert into @CUSTOMER 
select 'A1', 2, 'User1' union
select 'B1', 1, 'User2' union
select 'C1', 3, 'User3'

Declare @CustomerCategory TABLE (CustCategoryId INT, CategoryName varchar(10), StartTime time, EndTime time)
insert into @CustomerCategory
select 1, 'Category1', '8:15', '17:15' union
select 2, 'Category2', '7:30', '17:30' union
select 3, 'Category3', '8:15', '15:15'

Declare @Attendance table (Id int, CustomerId varchar(5), InTime time, OutTime time)
insert into @Attendance
select 1, 'A1', '7:30', '17:30' union
select 2, 'A1', '7:30', NULL union
select 3, 'B1', '8:15', NULL union
select 4, 'C1', '7:30', NULL

select * from @Customer
select * from @CustomerCategory
select * from @Attendance

merge @Attendance a
using 
(select c.CustomerId, cc.EndTime from @Customer c
    join @CustomerCategory cc on c.CustomerCategory = cc.CustCategoryId)x
on x.CustomerId = a.CustomerId
and a.OutTime is null
when matched then update
set a.OutTime = x.EndTime ;

select * from @Attendance

HTH!