在SQL中,我可以采取什么查询方式来获取2个主表和1个主详情表的数据?

问题描述 投票:-1回答:1

我有3张表People,Distribution,DistributionPeopleDetails如下。

enter image description here

我想检索人们何时得到最后一次帮助,何时应该得到下一次帮助。

我试着用不同的方式连接三个表,但没有给我预期的结果,我对SQL没有太多经验,所以可能我只是在想基本的连接,而它可能需要一些高级技巧,如group by等。谁能指导我一下?

到目前为止,我已经试过了。

select top 1 P.Name, d.DistributionDate as 'Next Scheduled Help'

from Peoples p left join [dbo].[DistributionPeopleDetails] dp on p.Id = 
dp.PeopleId
left join [dbo].[Distributions] d on dp.DistributionId = d.Id
where d.DistributionDate > GetDate() order by d.Id



select top 1 P.Name, d.DistributionDate as 'LastScheduled Help'

from Peoples p left join [dbo].[DistributionPeopleDetails] dp on p.Id = 
dp.PeopleId
left join [dbo].[Distributions] d on dp.DistributionId = d.Id
where d.DistributionDate < GetDate() order by d.Id

我得到了预期的结果 但我无法将这段查询放入我的SP中 我通过连接其他几张表来读取People的所有属性。

我想得到的是。

enter image description here

sql sql-server database master-detail
1个回答
0
投票

你是否在寻找连接和条件聚合,像这样?

select
    p.peopleId,
    p.name,
    max(case when d.distributionDate < getdate() then distributionDate end) lastDistibutionDate,
    min(case when d.distributionDate > getdate() then distributionDate end) nextDistibutionDate
from people p
left join distributionPeople dp on dp.peopleId = p.peopleId
left join distribution d on d.distributionId = dp.distributionId
group by p.peopleId, p.name

这给你每行一条记录,在 people,其中列 lastDistibutionDate 包含最新的过去 distributionDate 和列 nextDistibutionDate 是最接近的下一个 distributionDate.

© www.soinside.com 2019 - 2024. All rights reserved.