號以下查詢獲取了最新的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
爲什麼你在你的第三個獲得t1date的MAX查詢?另外,HAVING子句呢? – 007
@GordonLinoff - 我總是認爲三重連接的CTE比版本組更快 - 但我從來沒有測試過它。 – Hogan