0

我有一个查询,我正在尝试编写以返回数据库中出现的次数和实例,并按数据库定义的按周和产品分组。以下是我的查询:

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

这里需要更多信息

 dbo.getlatestmilestonedate() returns a datetime date in this format: mm:dd:yyyy hh:mm:ss

以及我目前拥有的数据样本表:

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

这些数据完全按照我想要的方式返回,因此除非需要完成最终目标,否则不需要对原始数据进行任何更改,即:

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

我认为我需要对此进行调整,但每次尝试时我只会遇到语法错误并且还不太了解枢轴语法。

4

1 回答 1

1

试试这个

select weekcompleted, product1, product2
from (your query) src
pivot (sum(CorrectionCount) for Product in ([Product1],[Product2])) p

如果您的产品可能会有所不同,那么您必须使用动态 SQL 构建上面的数据透视查询

declare @columns varchar(4000)
select @columns = '';
select @columns = ',[' + productname +']' 
    from (select distinct productname from products) v
select @columns = substring (@columns, 2, len(@columns))

declare @sql nvarchar(4000)
select @sql = 'select weekcompleted, ' + @columns 
+ ' from (your query) src '
+ ' pivot (sum(CorrectionCount) for Product in ('+@columns+')) p'

exec sp_executesql @sql
于 2012-10-17T22:02:44.417 回答