更新員工的標題我有2個表:SQL - 根據最近的職位
表1
CREATE TABLE #Table1(
EMPLOYEEID [nvarchar] (100) NULL,
Name [nvarchar] (100) NULL,
TITLE [nvarchar] (100) NULL)
INSERT INTO #Table1 (EMPLOYEEID, Name, TITLE) VALUES ('1','Tom','System Admin'), ('2','Bill','Server Admin'), ('3','John','Senior Server Admin'), ('4', 'Bob', 'IT Staff') , ('5', 'Jill', 'Senior IT Staff')
這給了我:
select * from #Table1
+------------+-------+---------------------+
| EMPLOYEEID | Name | Title |
+--------------------+---------------------+
| 1 | Tom | System Admin |
| 2 | Bill | Server Admin |
| 3 | John | Senior Server Admin |
| 4 | Bob | IT Staff |
| 5 | Jill | Senior IT Staff |
+--------------------+---------------------+
表2
CREATE TABLE #Table2(
EMPLOYEEnumber [nvarchar] (100) NULL,
Name [nvarchar] (100) NULL,
positiontitle [nvarchar] (100) NULL,
datepositionstart [date] NOT NULL)
INSERT INTO #Table2 (EMPLOYEEnumber, Name, positiontitle, datepositionstart) VALUES ('1','Tom','System Admin', '2014-07-03'), ('1','Tom','Server Admin', '2014-08-13'), ('1','Tom','Senior Server Admin', '2016-07-23'), ('2', 'Bob', 'IT Staff', '2014-07-03') , ('2', 'Bob', 'Senior IT Staff', '2016-10-15')
這給了我:
select * from #Table2
+----------------+-------+---------------------+-----------------+
| EMPLOYEEnumber | Name | positiontitle |datepositionstart|
+----------------+-------+--------------------+-----------------+
| 1 | Tom | System Admin | 2014-07-03 |
| 2 | Tom | Server Admin | 2014-08-13 |
| 3 | Tom | Senior Server Admin | 2016-07-23 |
| 4 | Bob | IT Staff | 2014-07-03 |
| 4 | Bob | Senior IT Staff | 2016-10-15 |
+------------------------+---------------------+-----------------+
如何根據表2中最新的職位更新table1員工職稱?
下面的代碼並沒有得到最近的日期,而不是我讓員工的副本從表2與同datepositionstart。
UPDATE Table1
SET E.TITLE = hre.[PositionTitle]
FROM Table1 E
JOIN Table2 hre on hre.EmployeeNumber = E.EMPLOYEEID
WHERE
E.Name = hre.Name
AND datepositionstart =
(SELECT MAX(datepositionstart)
FROM table2 hre
WHERE hre.EmployeeNumber = E.EMPLOYEEID)
預期結果:
+------------+-------+---------------------+
| EMPLOYEEID | Name | Title |
+--------------------+---------------------+
| 1 | Tom | Senior Server Admin |
| 2 | Bill | Server Admin |
| 3 | John | Senior Server Admin |
| 4 | Bob | Senior IT Staff |
| 5 | Jill | Senior IT Staff |
+--------------------+---------------------+
祝所有SQL問題進行了格式化這個樣子!你爲此贏得了讚賞。 –
是的,您在表格2中的數據看起來不正確... –
不,不要這樣做。改爲創建一個視圖。 (或者,也許有一個計算列。)但是爲什麼要存儲兩次相同的數據,從而導致數據不一致? – jarlh