2013-06-22 92 views
0

我有以下代碼。第二個和第三個最大值T-SQL

我對ColumnOfInterest感興趣。現在,下面的代碼將組合C1/C2/C3組合並僅輸出具有最新T2.Date ...的行嗎?

SELECT T1.C1,T1.C2,T1.C3 
    ,T1.ColumnofInterest (First Top Value) 
    ,T1.Date 
    ,T2.Date 
    ,MAX(T2.Date) AS DDate 
    ,COUNT(1) AS GroupCount 
FROM Table1 T1 INNER JOIN Table2 T2 
ON T1.ID = T2.ID 
GROUP BY T1.C1,T1.C2,T1.C2 
    ,T1.ColumnofInterest 
    ,T1.Date 
    ,T2.Date 
HAVING (T2.Date BETWEEN DATEADD(DD,-365,T1.Date) AND T1.Date) 

我想兩個欄位,讓我ColumnOfInterest2和ColumnofInterest3這將有第二和第三最新T2.Date值。

這可能嗎?

我想獲得這些值,我稍後將使用它來更新表格。

回答

1

號以下查詢獲取了最新的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 
+0

爲什麼你在你的第三個獲得t1date的MAX查詢?另外,HAVING子句呢? – 007

+1

@GordonLinoff - 我總是認爲三重連接的CTE比版本組更快 - 但我從來沒有測試過它。 – Hogan

相關問題