I have a query that i am trying to write to return the amount of times and instance occurs in a database and group by week and product as defined by the database. below is my query:
SELECT WeekCompleted, Product, COUNT(OrderNumber) as CorrectionCount FROM(
SELECT
p.Abbreviation as Product
,CAST(oi.OrderID as VARCHAR(MAX))+'.'+CAST(oi.OrderItemID as VARCHAR(MAX)) AS OrderNumber
,CASE
WHEN o.ClientID IN (56156, 56394)
THEN DATEADD(week, datepart(ww, dbo.GetLatestMilestoneDate(oi.OrderID, oi.OrderItemID, 80))
- 1, DATEADD(DAY, @@datefirst - DATEPART(weekday, CAST(YEAR(GETDATE()) AS VARCHAR)
+ '-01-01') - 6, CAST(YEAR(GETDATE()) AS VARCHAR) + '-01-01'))
ELSE DATEADD(week, datepart(ww, dbo.GetLatestMilestoneDate(oi.OrderID, oi.OrderItemID, 130))
- 1, DATEADD(DAY, @@datefirst - DATEPART(weekday, CAST(YEAR(GETDATE()) AS VARCHAR)
+ '-01-01') - 6, CAST(YEAR(GETDATE()) AS VARCHAR) + '-01-01'))
END AS WeekCompleted
,CASE
WHEN o.ClientID IN (56156,56394) THEN dbo.GetLatestMilestoneDate(oi.OrderID, oi.OrderItemID, 80)
ELSE dbo.GetLatestMilestoneDate(oi.OrderID, oi.OrderItemID, 130) END AS LastCompleted
FROM
OrderItems oi
LEFT JOIN OrderItemMilestones oim on oim.OrderID = oi.OrderID and oim.OrderItemID = oi.OrderItemID
JOIN Products p on p.ProductID = oi.ProductID
JOIN Orders o on o.OrderID = oi.OrderID
WHERE
oim.MilestoneID = 90
and QueueID = 0
) src
WHERE LastCompleted >= '2012-10-01'
GROUP BY WeekCompleted, Product
here is more info needed
dbo.getlatestmilestonedate() returns a datetime date in this format: mm:dd:yyyy hh:mm:ss
and a sample table of data i currently have:
WeekCompleted Product CorrectionCount
2012-09-30 00:00:00.000 Product1 5
2012-10-07 00:00:00.000 Product1 7
2012-10-14 00:00:00.000 Product1 7
2012-09-30 00:00:00.000 Product2 18
2012-10-07 00:00:00.000 Product2 28
2012-10-14 00:00:00.000 Product2 16
This data is returning exactly how i want it to so no change is needed to the original data unless needed to accomplish final goal, which is this:
WeekCompleted Product1 Product2
2012-09-30 00:00:00.000 5 18
2012-10-07 00:00:00.000 7 28
2012-10-14 00:00:00.000 7 16
I think i need to pivot this, but every time i try i only run into syntax errors and dont quite yet understand the pivot syntax.
Try this
If your products can vary then you have to build up the pivot query above using dynamic SQL