如何修复GROUP BY子句

时间:2016-07-27 09:27:53

标签: sql tsql group-by sql-server-2014

我有2个表,如下所示: enter image description here

现在的问题是: 如何查看显示最后一位所有者的详细信息?换句话说,我需要在tbl_Owners表中有MAX(StartDate)的人的详细信息? 我想找到每间公寓的最新主人。 我尝试了不同的方法,但我找不到这样做的方法。 我知道我需要在Group By子句中获取personID,该子句按AppID对记录进行分组,但我不能这样做

谢谢

5 个答案:

答案 0 :(得分:2)

试试这个

select t1.* from tbl_persons as t1 inner join 
(

    select t1.* from tbl_owners as t1 inner join 
        (
        select appid,max(startdate) as startdate from tbl_owners group by appid
        ) as t2
        on t1.appid=t2.appid and t1.startdate=t2.startdate
) as t2
on t1.personid=t2.personid 

答案 1 :(得分:1)

将此添加到您的查询中:

JOIN (select AppId, MAX(StartDate) as MAxStartDate
      from dbo.tbl_Owners
      group by PersonId) o2
   ON dbo.tbl_Owners.AppId= o2.AppId and
      dbo.tbl_Owners.StartDate = o2.MAxStartDate

上面的子查询返回每个AppId及其最新的StartDate。自我加入该结果将为您提供您想要的东西。

答案 2 :(得分:1)

您可以为此目的使用CTE

;WITH CTE AS
(
    SELECT AppID,PersonID,StartDate,
           ROW_NUMBER() OVER (PARTITION BY AppID ORDER BY StartDate DESC) RN
    FROM TableNAme
    GROUP BY AppID,PersonID,StartDate
)
SELECT * FROM CTE
WHERE RN=1

答案 3 :(得分:1)

SELECT dbo.tbl_Owners.*,dbo.tbl_Persons.PersonFullname FROM dbo.tbl_Owners
INNER JOIN
dbo.tbl_Persons ON dbo.tbl_Owners.PersonID=dbo.tbl_Persons.PersonID
GROUP BY dbo.tbl_Owners.StartDate HAVING MAX(StartDate);

在StartDate上使用GROUP BY代替PersonID。

答案 4 :(得分:1)

使用row_number

select t.*, p.* -- change as needed
from (select *, rn= row_number() over(partition by AppID order by StartDate desc)
      from dbo.tbl_Owners
   ) t
join dbo.tbl_Persons p on t.rn=1 and t.PersonId = p.PersonId 

使用交叉申请

select t.*, p.* -- change as needed
from dbo.tbl_Persons p 
cross apply (
   select top(1) * 
   from dbo.tbl_Owners o
   where o.PersonId = p.PersonId
   order by o.StartDate desc
   ) t