0

我有以下代码。

我对 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 的值。

这可能吗?

我想获取这些值,稍后我将使用它们来更新表。

4

1 回答 1

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
于 2013-06-22T03:31:41.007 回答