第二和第三大值T-SQL

时间:2013-06-22 03:17:38

标签: sql sql-server tsql

我有以下代码。

我对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 个答案:

答案 0 :(得分: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