转到每周总数

时间:2012-10-17 21:59:29

标签: sql sql-server tsql sql-server-2005

我有一个查询,我正在尝试编写以返回数据库中的实例和按实例在数据库定义的产品和产品中发生的次数和实例。以下是我的疑问:

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

我想我需要对此进行调整,但每次尝试时我都会遇到语法错误而且还不太了解数据透视语法。

1 个答案:

答案 0 :(得分: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