我有两张这样的表:
Table1 (Number column is unique)
Number | date
1234 2008-10-06 17:11:00
5678 2005-10-19 16:20:00
9023 2005-12-09 16:20:00
4243 2009-01-06 17:11:00
5234 2009-01-14 17:11:00
Table 2
Number | code
1234 A1
1234 B1
5678 A1
9023 A1
4243 C1
5234 C1
我正在尝试从这两个表中检索数据,这样我只得到表2中每个代码最近的一行(来自表1)。
根据这个例子,我的结果是:
1234 A1(因为那是最新日期的那个)
1234 B1(因为那是最新日期的那个)
5234 C1(因为那是最新日期的那个)
答案 0 :(得分:3)
Select Distinct T1.number, T2.code
From Table2 T2
Join Table1 T1
On T1.Number = T2.Number
And T1.date =
(Select Max(Date) From Table1
Where Number = T2.Number)
编辑:修复评论中提到的问题:
Select Z.Number, Z.Code
From (Select A.number, A.code, B.date
From Table2 A Join Table1 B
On B.Number = A.Number) Z
Where Z.Date =
(Select Max(Date)
From Table2 A Join Table1 B
On B.Number = A.Number
Where code = Z.Code)
答案 1 :(得分:1)
分析功能解决方案。这适用于Oracle;如果你正在使用另一个RDBMS,它可能无法正常工作。如果给定代码的多个行具有相同的日期,则会任意选择一个。
SELECT number, code FROM (
SELECT t1.number,
t1.code,
row_number() OVER ( PARTITION BY t1.code ORDER BY t2.date DESC ) date_sort_key
FROM t1, t2
WHERE t2.number = t1.number
)
WHERE date_sort_key = 1
将row()替换为row_number()将使其报告存在重复日期的多个条目。
答案 2 :(得分:1)
这是Dave的一个版本,适用于SQL Server
SELECT number, code FROM (
SELECT Table2.number,
Table2.code,
row_number() OVER ( PARTITION BY table2.code ORDER BY table1.date DESC ) date_sort_key
FROM table1, Table2
WHERE Table2.number = table1.number
) a
WHERE date_sort_key = 1
答案 3 :(得分:0)
这适用于SQL SERVER
CREATE table Table1 (number int, date datetime)
INSERT Table1 VALUES (1234, '2008-10-06 17:11:00')
,(5678, '2005-10-19 16:20:00')
,(9023, '2005-12-09 16:20:00')
,(4243, '2009-01-06 17:11:00')
,(5234, '2009-01-14 17:11:00')
CREATE table Table2 (number int, code varchar(2))
INSERT Table2 VALUES (1234, 'A1 ')
,(1234, 'B1')
,(5678, 'A1')
,(9023, 'A1')
,(4243, 'C1')
,(5234, 'C1')
SELECT DISTINCT
a.number
,a.code
FROM Table2 a
INNER JOIN Table1 b ON a.number = b.number
INNER JOIN (
SELECT
t2.code
,MAX(t1.date) as date
FROM Table2 t2
INNER JOIN Table1 t1
ON t1.Number = t2.Number
GROUP BY t2.code
) c ON b.date = c.date