只是想知道任何人都可以看到编写此查询的更简洁的方法。这对我来说似乎有很多重复,但我看不到更简单的方法来编写它。它正在撤回年初至今的数据。
输出如下所示:
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]