这个查询返回的正是我需要的,但我也试图从中创建一个数据透视表。我希望能够对 CASE 子句中定义为 SLAStatus 的列进行求和(不知道这是否可能)以及计算 OrderID 列以及计算(SLAStatus 列的总和)/(OrderID 列的计数)返回具有 SLA 的订单的百分比。一直在网上到处找,但似乎无法弄清楚
SELECT oi.OrderID, o.Address1 as StreetAddress, c.Name as County, o.State, p.Abbreviation, oi.OrderDate as Dateentered,
DATEADD(dd, DATEDIFF(dd, 0, oi.DeliveredDate), 0) as DateCompleted, DATEADD(dd, DATEDIFF(dd, 0, oi.RequiredByDate), 0) as EstimatedDeliveryDate,
CASE
WHEN oi.DeliveredDate <= oi.RequiredByDate THEN '1'
ELSE '0'
END AS SLAStatus,
cl.Name as Client, clb.Name as Client2, v.ContactFirstName + ' ' + v.ContactLastName as Appraiser
FROM OrderItems oi
JOIN Orders o on o.OrderID = oi.OrderID
JOIN Counties c on c.FIPS = o.FIPS
JOIN Products p on p.ProductID = oi.ProductID
JOIN Clients cl on cl.ClientID = o.ClientID
JOIN ClientBranches clb on clb.ClientID = cl.ClientID
JOIN Vendors v on v.VendorID = oi.VendorID
JOIN Milestones m on m.MilestoneID = oi.LastMilestoneID
WHERE cl.Name not like '%TEST%'
and '2012-03-01' <=
(select MAX(MilestoneDate)
from OrderItemMilestones
where OrderID = oi.OrderID
and OrderItemID = oi.OrderItemID
and MilestoneID in (100,130,140,150))
and '2012-04-10' >=
(select MAX(MilestoneDate)
from OrderItemMilestones
where OrderID = oi.OrderID
and OrderItemID = oi.OrderItemID
and MilestoneID in (100,130,140,150))