|
有人告诉我解决以下情况。) s: Q4 d. ?9 L7 V1 I* j
我需要基于我需要基于
- W4 M' d5 i% F' LEmployeeID返回最后更新日期和最后更新者列。此查询必须在父表和所有子表中搜索最新条目,并返回按钮ID分组列。我正在寻找一种不使用的列。UNION
7 h2 X! k3 r7 X! l2 o$ MALL连接父表和子表的解决方案,解决两个不同用户可以在不同表中相同的情况EmployeeID输入最新记录(外键或主键)。4 A& z$ i6 [0 h: Q7 q
例如,Jim今天更新了Employee表的EmployeeID 1,Paul也更新了EmployeeID, N- v+ p, @3 Q! z5 y/ V
1的Employee_Address表。基于该EmployeeID 1由不同用户输入新日期有两个记录,由不同的用户输入。
/ e5 @( N; R" h0 n# D* J' P- S请参考架构和所有脚本,我找不到最后一个更新者部分。" W6 x8 N( C( ?; {
CREATE TABLE EMPLOYEE( EMPLOYEE_ID INT, NAME VARCHAR(100), LAST_UPDATED_BY VARCHAR(200), LAST_UPDATED_DT DATE)CREATE TABLE EMPLOYEE_AWARD( AWARD_ID INT, EMPLOYEE_ID INT, AWARD_NAME VARCHAR(100), LAST_UPDATED_BY VARCHAR(200), LAST_UPDATED_DT DATE)CREATE TABLE EMPLOYEE_ADDRESS( ADDRESS_ID INT, EMPLOYEE_ID INT, "ADDRESS" VARCHAR(100), LAST_UPDATED_BY VARCHAR(200), LAST_UPDATED_DT DATE)INSERT INTO EMPLOYEE VALUES (1,'Paul Smith','GomesR Francis Jones','KellyR (3)Paul Bo','GomesR (4)Ed Li','TurnerR‘1/19/2012’INSERT INTO EMPLOYEE_AWARD VALUES Employee of the Month','GomesR6/22/2015Employee of the Month','KellyR5/20/2013), Employee of the Quater','GomesR 3,'Employee of the Month','TurnerR Employee of the Month','KellyR11/11/2011INSERT INTO EMPLOYEE_ADDRESS VALUES Address 1','GomesR Address 2','TurnerR5/28/2015), Address 3','TurnerR Address 4','GomesR6/14/2014SELECT D.EMPLOYEE_ID,Max(D.LAST_UPDATED_DT) LAST_UPDATED_DT--,D.LAST_UPDATED_BYFROM EMPLOYEE AINNER JOIN ( SELECT EMPLOYEE_ID,LAST_UPDATED_DT,LAST_UPDATED_BY FROM EMPLOYEE UNION ALL SELECT EMPLOYEE_ID,LAST_UPDATED_DT,LAST_UPDATED_BY FROM EMPLOYEE_AWARD UNION ALL SELECT EMPLOYEE_ID,LAST_UPDATED_DT,LAST_UPDATED_BY FROM EMPLOYEE_ADDRESS AS DON A.EMPLOYEE_ID = D.EMPLOYEE_IDGROUP BY D.EMPLOYEE_ID * `6 f3 i$ u, H
解决方案:
6 `; q" v1 t# j* t9 w- Q9 ?0 Q 如果两个不同的用户在同一天根据需要更新一个员工,他们将返回两行。( K- c. g+ ]7 W; L9 O
select employee_id, last_updated_dt, last_updated_by from (select x.*, max(last_updated_dt) over(partition by employee_id) as max_last_updated_dt from (select employee_id, last_updated_dt, last_updated_by from employee union all select employee_id, last_updated_dt, last_updated_by from employee_award union all select employee_id, last_updated_dt, last_updated_by from employee_address) x) x where last_updated_dt = max_last_updated_dt小提琴:http* Q+ `8 y5 u; i! n6 r
://sqlfiddle.com/#!3/a4503c/1/06 J; K+ J. Q7 m5 o
不要避免使用union all。数据位于三个不同的表中,所以这是适当的应用union all。 |
|