2017-01-30 84 views
0

我一直在試圖運行一個支點查詢,但我沒有努力,我很新的這一切,所以請耐心等待樞紐和內部連接

我要的是回到每個月的數量值,一月,二月...十二月,每個PartRef

這是我

SELECT PartRef 
     , Year 
     , fMonth 
     , sum(Quantity) as Quantity 

FROM(SELECT PartRef 
       , year(DateClosed) as Year 
       , month(DateClosed) as Month 
       , SUM(fldShipped) as Quantity 

    FROM PartsInvoice 
    INNER JOIN Requests ON PartsInvoice.fID = Requests.WorkItemRef 
    INNER JOIN PartsLine ON Requests.ID = PartsLine.RequestRef 

    WHERE Closed = 1 and DateClosed > DateAdd(mm, DateDiff(mm, 0, GetDate()) -12, 0) 
    GROUP BY PartRef, year(DateClosed), month(DateClosed) 

) as SalesHits 

PIVOT (

SUM(NOT SURE)FOR NOT SURE IN ([Jan],[Feb],[Mar],[Apr],[May],[June],[July],[Ago],[Sep],[Oct],[Nov],[Dec]) 
)AS Hits 

GROUP BY PartRef, Year, Month 

回答

0

這裏有一個例子是如何像你這樣一個表的工作原理。

declare @table table(
    partref int, 
    year int, 
    month nvarchar(50), 
    quantity int 
) 

insert into @table values 
(1,2016,'jan',12), 
(1,2016,'feb',12), 
(2,2016,'jan',12), 
(2,2016,'feb',12), 
(1,2016,'jan',12) 

select PartRef 
     , year 
     , sum([jan]) 'Jan',sum([feb]) 'Feb' 
     ,sum([mar]),sum([apr]),sum([may]),sum([jun]),sum([jul]) 
     ,sum([aug]),sum([sep]),sum([oct]),sum([nov]),sum([dec]) 
     from(
     SELECT PartRef 
       , year 
       , [jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct],[nov],[dec] 
       from @table 
       PIVOT (
     SUM(quantity)FOR month IN ([jan],[feb],[mar],[apr],[may],[jun],[jul],[aug],[sep],[oct],[nov],[dec]) 
     )AS Hits 
) as t 
group by PartRef,year 
+0

感謝

SELECT,我已經有表中的數據和你刪除了INNER JOIN,?? –

+0

我簡化了查詢,使其能夠處理簡單的數據,您可以添加數據所需的條件 – AlbertoCh

0

這裏是我的查詢的全部範圍,我相信我得到它的工作:)的答覆*

FROM(SELECT PartRef 
    , year(DateClosed) as Year 
    , month(DateClosed) as Month 
    , SUM(Shipped) as Quantity 

    FROM PartsInvoice 
    INNER JOIN Requests ON PartsInvoice.ID = Requests.WorkItemRef 
    INNER JOIN PartsLine ON Requests.ID = PartsLine.RequestRef 

    WHERE HasClosed = 1 and DateClosed > DateAdd(mm, DateDiff(mm, 0, GetDate()) -13, 0) 
    GROUP BY PartRef, year(DateClosed), month(DateClosed) 

    UNION ALL 

    --RO 
    SELECT PartRef 
    , year(DateClosed) as Year 
    , month(DateClosed) as Month 
    , SUM(Shipped) as Quantity 

    FROM RepairOrder 
    INNER JOIN Requests ON RepairOrder.ID = Requests.WorkItemRef 
    INNER JOIN PartsLine ON Requests.ID = PartsLine.RequestRef 

    WHERE Status = 3 and DateClosed > DateAdd(mm, DateDiff(mm, 0, GetDate()) -13, 0) 
    GROUP BY PartRef, year(DateClosed), month(DateClosed) 

    UNION ALL 

    -- Historical Hits 
    SELECT PartRef 
    , year(date) as Year 
    , month(Date) as Month 
    , SUM(Quantity) as Quantity 

    FROM PartsHistoricalHits 

    WHERE Date > DateAdd(mm, DateDiff(mm, 0, GetDate()) -13, 0) 
    GROUP BY PartRef, year(Date), month(Date) 


) as SalesHits 

    PIVOT (

    COUNT (Quantity)FOR fldMonth IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13]) 
)AS Hits