Some time ago I came across a interesting problem, we were measuring or delivery performance based on the whole order and not the lines itself, simply put if one line was late the whole order was to be considered late, this poses a problem as most of the data in the data warehouse was on line level.
I struggled some time before I came up with this solution, I even considered using a cursor before finally decided to go with this
select
der.[Order ID]
,case when SUM(der.Late) = 0 then 0 else 1 end as [Late]
,MAX(der.ShipDate) as [ShipDate]
,AVG(der.Days) as [AvgDays]
,COUNT(der.[Order ID]) as [NoOfTrans]
,der.DataAreaID
,der.Company
from(
select
t1.[Order ID]
,case when DATEDIFF(dd, t1.[Last packing slip date]
,t1.[Original Confirmed Shipping Date]) < 0 then 1 else 0 end as [Late]
,t1.[Last packing slip date] as [ShipDate]
,DATEDIFF(dd, t1.[Last packing slip date]
,t1.[Original Confirmed Shipping Date]) as [Days]
,upper(t1.DataAreaID) as [DataAreaID]
,t1.Company
from SalesOrderStatistics t1 inner join Items t2 on t1.ItemID = t2.[Item ID] and t1.DataAreaId = t2.DataAreaID
where t1.[Last packing slip date] >= '2011-01-01'
and t1.[Order status] in('Delivered','Invoiced')
) as der
group by der.Company, der.DataAreaID, der.[Order ID]
order by der.[Order ID]