按周的Sql Server查询结果

时间:2012-08-01 06:30:34

标签: sql-server sql-server-2008

我有以下表格

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

1 个答案:

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

让我知道它是否适合你。