2014-11-03 100 views
0

希望簡單的MS SQL問題!我有四個表:跨多個表的SQL Server連接

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'的總人數。 返回的行數必須與tripI相關的行程數量,其中portfolioId = 1,由tripName排序。

想法?我正在使用MS SQL,對SQL有一個基本的瞭解,而這正在推動着我的香蕉。

回答

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

+0

我結束了使用CTE的 - 他們已經永遠地改變了我的生活MSSQL。 – Richard 2015-05-05 15:20:49

0

一種選擇是,你可以使用子查詢,以獲得COUNTA和countB,所以查詢看上去像下面的一些事情:

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 
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