我需要SELECT查询的帮助,我需要在其中加入另一个表并获取最大日期记录。我已经创建了示例来演示。我的最后一个SELECT是不正确的,我需要指导来修复它,或者在Sql server 2014中有更好的方法
CREATE TABLE #EmpTable
(
EmpNum INT,
colA VARCHAR(5) NULL,
colB VARCHAR(5) NULL
)
CREATE TABLE #EmpDetailTbl
(
EmpNum INT,
Name VARCHAR(10),
Department VARCHAR(10) NULL,
ReportDate DATETIME NOT NULL
)
INSERT INTO #EmpTable
VALUES (101, 'val11', 'Val21'), (102, 'val12', 'Val21'), (103, 'val13', 'Val23');
INSERT INTO #EmpDetailTbl
VALUES (101, 'emp101', 'Dept1', '05/01/2018'), (101, 'emp101', 'Dept2', '06/01/2018'),
(101, 'emp101', 'Dept1', '05/01/2017'), (102, 'emp102', 'Dept3', '04/01/2018'),
(102, 'emp102', 'Dept1', '05/01/2018')
--select * from #EmpDetailTbl
--select * from #EmpTable
SELECT
a.EmpNum, Name, ColA, ColB, Department
FROM
#EmpTable a
LEFT OUTER JOIN
#EmpDetailTbl b ON a.EmpNum = b.EmpNum
AND ReportDate = (SELECT MAX(ReportDate)
FROM #EmpDetailTbl
a.EmpNum = b.EmpNum)
答案 0 :(得分:2)
使用rank()
分析函数根据报告日期枚举行,然后仅为每位员工选择第一行:
SELECT EmpNum, Name, ColA, ColB, Department
FROM (
SELECT
a.EmpNum, b.Name, a.ColA, a.ColB, b.Department,
rank() over (partition by a.EmpNum order by b.ReportDate desc) as rn
FROM #EmpTable a
LEFT JOIN #EmpDetailTbl b ON
a.EmpNum = b.EmpNum
) t
WHERE rn = 1;
此查询将处理关系:如果员工的记录超过1条且具有相同日期且也恰好是最大值,则会全部显示。
答案 1 :(得分:1)
如果我理解正确,你可以试试这个以获得MaxDate行。
使用exists
按MAX(b1.ReportDate)
EmpNum
select a.EmpNum, Name, ColA, ColB, Department
FROM #EmpTable a
LEFT JOIN #EmpDetailTbl b on a.EmpNum = b.EmpNum
WHERE exists (
SELECT 1
FROM #EmpDetailTbl b1
WHERE b1.EmpNum = b.EmpNum
GROUP BY b1.EmpNum
HAVING MAX(b1.ReportDate) = b.ReportDate
)
sqlfiddle:https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=a3deade95dbd25d9cadadee37e16d9c6
<强>结果强>
EmpNum Name ColA ColB Department
101 emp101 val11 Val21 Dept2
102 emp102 val12 Val21 Dept1
103 emp103 val13 Val23 Dept1
答案 2 :(得分:0)
ReportDate应该是a.ReportDate