包括聚合函数结果中其他列的数据

时间:2014-04-15 09:58:24

标签: sql sql-server sql-server-2008

client_ref  matter_suffix    date_opened
1           1                1983-11-15 00:00:00.000
1           1                1983-11-15 00:00:00.000
1           6                2002-11-18 00:00:00.000
1           7                2005-08-01 00:00:00.000
1           9                2008-07-01 00:00:00.000
1           10               2008-08-22 00:00:00.000
2           1                1983-11-15 00:00:00.000
2           2                1992-04-21 00:00:00.000
3           1                1983-11-15 00:00:00.000
3           2                1987-02-26 00:00:00.000
4           1                1989-01-07 00:00:00.000
4           2                1987-03-15 00:00:00.000

我有上表,我只是想以下面的格式返回为每个客户开设的最新事项:

client_ref  matter_suffix    Most Recent
1          10                 2008-08-22 00:00:00.000
2          2                  1992-04-21 00:00:00.000
3          2                  1987-02-26 00:00:00.000
4          1                  1989-01-07 00:00:00.000

我可以执行一个非常简单的查询来返回最新的(如下所示),但每当我尝试包含matter_suffix数据(必要)时,我都会遇到问题。

提前致谢。

select client_ref,max (Date_opened)[Most Recent] from archive a
group by client_ref
order by client_ref

4 个答案:

答案 0 :(得分:0)

这不起作用吗?

select client_ref,matter_suffix,max (Date_opened)[Most Recent] from archive a
group by client_ref,matter_suffix
order by client_ref

答案 1 :(得分:0)

您可以使用ROW_NUMBER函数获取每个client_ref的最新记录:

SELECT  client_ref, matter_suffix, Date_opened
FROM    (   SELECT  client_ref, 
                    matter_suffix,
                    Date_opened,
                    RowNumber = ROW_NUMBER() OVER(PARTITION BY client_ref 
                                                    ORDER BY Date_opened DESC)
            FROM    archive a
        ) a
WHERE   RowNumber = 1;

如果要返回具有相同最大打开日期的多行的所有行,则可以使用RANK:

SELECT  client_ref, matter_suffix, Date_opened
FROM    (   SELECT  client_ref, 
                    matter_suffix,
                    Date_opened,
                    RowNumber = RANK() OVER(PARTITION BY client_ref 
                                                    ORDER BY Date_opened DESC)
            FROM    archive a
        ) a
WHERE   RowNumber = 1;

答案 2 :(得分:0)

在SQL 2012中,有一些方便的功能可以使这更容易,但在SQL 2008中,您需要以旧方式执行此操作:

找到最新的:

 SELECT client_ref,MAX(date_opened) last_opened
 FROM YourTable
 GROUP BY client_ref

现在加入到那个回来:

SELECT client_ref,matter_suffix, date_opened
FROM YourTable YT
INNER JOIN
(
 SELECT client_ref,MAX(date_opened) last_opened
 FROM YourTable
 GROUP BY client_ref
) MR
ON  YT.client_ref = MR.client_ref
AND YT.date_opened = MR.last_opened

答案 3 :(得分:0)

select client_ref,max (matter_suffix),RN = ROW_NUMBER()OVER(PARTITION BY matter_suffix ORDER BY Date_opened desc) from archive a
WHERE RN = 1
group by client_ref,Date_opened
order by client_ref,Date_opened