否。以下查询获取具有最新 t2 日期的行:
select c1, c2, c3, ColumnOfInterest, t1date, t2date, GroupCount
from (SELECT T1.C1, T1.C2, T1.C3, T1.ColumnofInterest,
T1.Date as t1date, T2.Date as t2date,
row_number() over (partition by t1.c1, t1.c2, t1.c3 order by t2.date desc) as seqnum,
count(*) over (partition by t1.c1, t1.c2, t1.c3) as GroupCount
FROM Table1 T1 INNER JOIN
Table2 T2
ON T1.ID = T2.ID
) t
where seqnum = 1
很难解释您的查询是做什么的,但是因为它是按日期分组的,所以计数可能总是 1。这会为每个组分配一个序号(基于partition by
子句)。最近日期的值为 1 ( order by t2.date desc
)。
以下版本获取不同行的第二个和第三个日期:
select c1, c2, c3, ColumnOfInterest, t1date, t2date, GroupCount
from (SELECT T1.C1, T1.C2, T1.C3, T1.ColumnofInterest,
T1.Date as t1date, T2.Date as t2date,
row_number() over (partition by t1.c1, t1.c2, t1.c3 order by t2.date desc) as seqnum,
count(*) over (partition by t1.c1, t1.c2, t1.c3) as GroupCount
FROM Table1 T1 INNER JOIN
Table2 T2
ON T1.ID = T2.ID
) t
where seqnum in (1, 2, 3);
而这个版本将它们放在同一行:
select c1, c2, c3, ColumnOfInterest, max(t1date), max(t2date), count(*) as GroupCount
max(case when seqnum = 1 then ColumnofInterest end) as ColumnofInterest_1,
max(case when seqnum = 2 then ColumnofInterest end) as ColumnofInterest_2,
max(case when seqnum = 3 then ColumnofInterest end) as ColumnofInterest_3
from (SELECT T1.C1, T1.C2, T1.C3, T1.ColumnofInterest,
T1.Date as t1date, T2.Date as t2date,
row_number() over (partition by t1.c1, t1.c2, t1.c3 order by t2.date desc) as seqnum,
count(*) over (partition by t1.c1, t1.c2, t1.c3) as GroupCount
FROM Table1 T1 INNER JOIN
Table2 T2
ON T1.ID = T2.ID
) t
group by c1, 2, c3