此查询正在返回我需要的内容,但我也试图从中创建一个数据透视表。我希望能够在CASE子句中对已定义为SLAStatus的列进行SUM(不知道是否可能),以及计算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))
答案 0 :(得分:0)
我建议使用公用表表达式(CTE)。只需将原始查询包装在CTE中,即可进行所需的分组。
with originalCTE as
(
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))
)
select sum(SLAStatus), sum(SLAStatus) / count(orderID)
from originalCTE;
如果我正确理解你在寻找什么,那么我就是这样做的。希望这会有所帮助。