このクエリを作成するためのより適切な方法を誰かが見ることができるかどうか疑問に思っています。私には何度も繰り返しているように思えますが、もっと簡単に書く方法がわかりません。年初来のデータを引き戻しています。
出力は次のようになります。
name Total New Drives Total New Sales Total Used Drives Total Used Sales
Alan 41 31 15 93
Pascal 45 51 35 33
クエリは次のとおりです。
select sp.name, x.ttlNewTestDrives, x.ttlNewSales, y.ttlUsedTestDrives, y.TtlUsedSales
from
(
select ts.SalesPersonID, ttd.TotalTestDrives as TtlNewTestDrives ,ts.TotalSales as TtlNewSales
from
(
select sp.[SalesPersonID], count([TestDriveID]) as TotalTestDrives
from SalesPeople sp
join TestDrives td
on sp.[SalesPersonID] = td.[SalesPerson_SalesPersonID]
join cars c on
c.[CarID] = td.[Car_CarID]
where c.CarType = 'New'
group by sp.[SalesPersonID]
) as ttd
full outer join
(
select sp.[SalesPersonID], count(SaleID) as TotalSales
from Sales s
join SalesPeople sp
on s.[Salesperson_SalesPersonID] = sp.[SalesPersonID]
join cars c on
s.[Car_CarID] = c.[CarID]
where c.CarType = 'New'
group by sp.[SalesPersonID]
) as ts
on ts.[SalesPersonID] = ttd.[SalesPersonID]
) as x
full outer join
(
select ttd.SalesPersonID, ttd.TotalTestDrives as TtlUsedTestDrives ,ts.TotalSales as TtlUsedSales
from
(
select sp.[SalesPersonID], count([TestDriveID]) as TotalTestDrives
from SalesPeople sp
join TestDrives td
on sp.[SalesPersonID] = td.[SalesPerson_SalesPersonID]
join cars c on
c.[CarID] = td.[Car_CarID]
where c.CarType = 'Used'
group by sp.[SalesPersonID]
) as ttd
full outer join
(
select sp.[SalesPersonID], count(SaleID) as TotalSales
from Sales s
join SalesPeople sp
on s.[Salesperson_SalesPersonID] = sp.[SalesPersonID]
join cars c on
s.[Car_CarID] = c.[CarID]
where c.CarType = 'Used'
group by sp.[SalesPersonID]
) as ts
on ts.[SalesPersonID] = ttd.[SalesPersonID]
) y
on x.[SalesPersonID] = y.[SalesPersonID]
join SalesPeople sp
on x.[SalesPersonID] = sp.[SalesPersonID]