SQL Server跨多个表连接

时间:2014-11-03 02:55:11

标签: sql sql-server sql-server-2012

希望是一个简单的MS SQL问题!我有四张桌子:

Portfolio:
int portfolioId, string portfolioName
1,'PortFolio 1'

Trip:
int tripId, int portfolioId, int tripType, int maxPeople, string tripName
1, 1, 1, 20, 'Trip A'
2, 1, 1, 21, ’Trip B'
3, 1, 2, 22, ’Trip C'

Person:
int personId, int personStatus, string personName
1, 14, ‘Person 1'
2, 15, ‘Person 2'
3, 16, ‘Person 3'

TripPerson:
int personId, int tripId
1, 1
1, 3
2, 1
2, 2

对于给定的portfolioId,我正在尝试编写一个干净的查询,它将为我提供以下列:

tripId, countA, countB, tripType, tripName

其中: CountA:是旅行中的人数总数。 CountB:是那次旅行中至少还有一次类型为'2'的人的总人数。 返回的行数必须与投资组合相关的行程数相匹配,其中portfolioId = 1,按tripName排序。

思考?我正在使用MS SQL,对SQL有基本的了解,这就是我的香蕉。

3 个答案:

答案 0 :(得分:1)

您可以将查询编写为:

With CTE1 as
(
-- Total number of persons on a trip:
select count(T.personId) as CountA , tripId
from TripPerson T
group by T.tripId
),
CTE2 as 
(
    -- Total number of people who are on a trip that have also been on 
    -- at least one other trip with type of '2'.
    select Count (T2.personId)as CountB , CTE1.tripId ,CTE1.CountA
    from TripPerson T2
    inner join  TripPerson T3 on T2.personId = T3.personId and T3.tripId =2
    right join CTE1 on CTE1.tripId = T2.tripId
    group by CTE1.tripId,CTE1.CountA
) 
select CTE2.tripId, CTE2.CountA, CTE2.CountB, Trip.tripType, Trip.tripName
from CTE2
inner join Trip on Trip.tripId = CTE2.tripId
inner join Portfolio P on P.portfolioId = Trip.portfolioId

DEMO

答案 1 :(得分:0)

一个选项是你可以使用子查询来获取countA和count,查询看起来像下面的一些事情:

select trip.tripId, trip.tripType, trip.tripName, 
(select count(personId) from TripPerson where tripId = trip.tripId) as countA, 
(select count(personId) from TripPerson where tripId IN (trip.tripId, 2)) as countB 
from Trip trip 
where portfolioId = 1 order by trip.tripName

答案 2 :(得分:0)

这将通过加入tripperson找到计数并再次使用左连接来找到已经多次旅行的同一个人来获得结果。

SELECT t.tripId, count(p.personid) countA, count(p2.personid) countB, 
       t.tripType, t.tripName, t.portfolioid
FROM TRIP t
JOIN TripPerson p ON p.tripid = t.tripid
LEFT JOIN (select tp.personid, count(*) cnt FROM TripPerson tp group by tp.personid) p2 
     ON p2.personid = p.personid and p2.cnt > 1
group by t.tripId, t.tripType, t.tripName, t.portfolioid