2012-08-01 173 views
0

我有以下各表SQL Server查詢結果通過

Order 

ID OrderDate Quantity Item 
1 1 jan 2012  5  A 
2 6 jan 2012  10  A 
3 9 jan 2012  3  B 
4 16 jan 2012 2  C 

Order Shipped 

ID SuppliedOn Quantity Item OrderId 
1 7 Jan 2012  3  A  1 
2 9 Jan 2012  2  A  1 
3 9 Jan 2012  10  A  2 
4 17 jan 2012  3  B  3 

我想列出秩序的形成,在周提供

Week      Total_Order_got Total_Order_Supplied Item 
1st week Jan(2 jan 2012)  15     3    A 
2nd Week Jan(9 jan 2012)   0     12    A 
2nd Week Jan(9 jan 2012)   3     0    B 
3rd Week Jan(16 jan 2012)  0     3    B 
3rd Week Jan(16 jan 2012)  2     0    C 

回答

0

這裏順序是解決方案:

Select my.Mydate, MAX(ThisWeekStart) as ThisWeekStart , SUM(oqty) as oqty,SUM(sqty) as sqty,item from 
(Select DatePart(week,o.orderdate) as Mydate, 
    dateadd(wk, datediff(wk, 0, o.orderdate), 0) as ThisWeekStart, 
o.qty as oqty, 0 as sqty, o.item 
FROM [order] o 
UNION 
SELECT DatePart(week,s.suppliedon) as suppliedon, 
dateadd(wk, datediff(wk, 0, s.suppliedon), 0) as ThisWeekStart, 
0 as oqty, s.qty as sqty, s.item 
FROM supply s) as my 
GROUP BY my.Mydate, item 

讓我知道什麼時候呃它爲你工作。