T-SQL:GROUP BY,但保留一个未分组的列(或重新加入它)?

问题描述 投票:0回答:3

我在SQL Server 2008上,并且无法按照我想要的方式查询审计表。

该表显示每次有新ID进入时,以及每次ID类型更改时

Record #    ID          Type    Date
1           ae08k       M       2017-01-02:12:03
2           liei0       A       2017-01-02:12:04
3           ae08k       C       2017-01-02:13:05
4           we808       A       2017-01-03:20:05

我想在某个特定日期生成每个ID状态的快照。我的想法是这样的:

SELECT
    ID
    ,max(date) AS Max

FROM
    Table

WHERE
    Date < 'whatever-my-cutoff-date-is-here'

GROUP BY
    ID

但那会失去Type列。如果我将类型列添加到我的GROUP BY中,那么对于日期之前的所有类型,我会自然地获得每个ID的重复行。

所以我在考虑运行表的第二个版本(通过公共表表达式),然后将其连接到以获取Type。

在我上面的查询中,我必须加入的是ID和日期。不知何故,如果日期过于接近,我最终会得到重复的结果(如上所述,ae08k会为每种类型显示一次)。那或者我只是非常困惑。

基本上我在SQL中做的就是左连接,分组和公用表表达式(然后左连接)。在这种情况下我想要的是什么?

sql-server tsql group-by common-table-expression
3个回答
2
投票

使用row_number()

select *  
from ( select *
            , row_number() over (partition by id order by date desc) as rn 
       from table 
       WHERE Date < 'whatever-my-cutoff-date-is-here'
     ) tt
where tt.rn = 1

0
投票

我想知道在某个特定日期,每种类型的ID有多少。

好吧,为此您在类型上使用COUNTGROUP BY

SELECT Type, COUNT(ID)
FROM Table
WHERE Date < 'whatever-your-cutoff-date-is-here'
GROUP BY Type

0
投票

根据你在Zohar Peled的评论回答你可能正在寻找这样的事情:

; with cte as (select distinct ID from Table where Date < '$param')
select [data].*, [data2].[count]
from cte
cross apply 
( select top 1 *
  from Table
  where Table.ID = cte.ID
  and Table.Date < '$param'
  order by Table.Date desc
) as [data]
cross apply
( select count(1) as [count]
  from Table
  where Table.ID = cte.ID
  and Table.Date < '$param'
) as [data2]
© www.soinside.com 2019 - 2024. All rights reserved.