找到最后一个参与项目的人(grouping/having sql?)

Finding the last person working on a project (grouping/having sql?)

我正在尝试弄清楚如何查询最后(日期)在项目(项目)上工作的最后一个人(姓名)。

目录A

     (id) | project  | name     | date
----------+----------+---------------------
        1 | ProjA    | Joe      | 1-1-2011
        2 | ProjA    | Sally    | 2-2-2011
        3 | ProjA    | Joe      | 3-3-2011
        4 | ProjB    | Sally    | 4-4-2011
        5 | ProjB    | Bert     | 5-5-2011

在这种情况下,我需要的结果是:

     (id) | project  | name     | date
----------+----------+-------------
        3 | ProjA    | Joe      | 3-3-2011
        5 | ProjB    | Bert     | 5-5-2011

到目前为止我得到的是:

SELECT project, max(date) FROM TableA 

这会得到项目和日期,但不会得到人员的 ID 和姓名。

SELECT id, project, name, max(date) FROM TableA 

这将(显然)导致错误

Column 'id' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.

我有点生疏了,迷路了。

你需要 row_number() :

select a.*
from (select a.*, row_number() over (partition by a.project order by a.date desc) as seq
      from tablea a
     ) a
where a.seq = 1;

如果日期有 关系 ,那么您需要 dense_rank()

编辑: 我现在理解正确了,但不确定这是否有帮助。我认为这样更简单,但如果您有多个用户在同一天处理一个项目,可能会变得混乱:

SELECT project, name, date
FROM (
SELECT *, max_date = MAX(date) OVER (PARTITION BY project)
FROM TableA) T 
WHERE date = max_date

干杯 安德烈亚斯

Disregard this: I might not understand the question but this should do the tick:

SELECT id, project, name, max(date) FROM TableA
GROUP BY id, project, name

试试这个,

DECLARE @Temp_Data TABLE
(
    id int ,project varchar(30),[name] varchar(30),[date] date
)

INSERT INTO @Temp_Data
SELECT 1,'ProjA','Joe','1-1-2011' UNION ALL
SELECT 2,'ProjA','Sally','2-2-2011' UNION ALL
SELECT 3,'ProjA','Joe','3-3-2011' UNION ALL
SELECT 4,'ProjB','Sally','4-4-2011' UNION ALL
SELECT 5,'ProjB','Bert ','5-5-2011'

;WITH CTE_Temp_Data AS
(
    SELECT id, project,[name],[date],ROW_NUMBER() OVER (PARTITION BY project ORDER BY [date] DESC) AS R_NO
    FROM @Temp_Data
)

SELECT id, project,[name],[date] 
FROM CTE_Temp_Data
WHERE R_NO=1