如何按周计算数据组,但从头开始总和?

时间:2015-07-03 12:43:58

标签: sql tsql sum divide week-number

我有一个这样的数据库:

Entry_No    Week    Registering_Date    Bin_Code    Item_No  Quantity
=====================================================================
1           26      6/26/2015           BIN 1       A         10
2           26      6/26/2015           BIN 1       B         20
3           26      6/26/2015           BIN 1       C         30
4           26      6/26/2015           BIN 1       D         40 
5           27      6/29/2015           BIN 1       A         -3 
6           27      6/29/2015           BIN 2       A          3  
7           27      6/29/2015           BIN 1       A         -2
8           27      6/29/2015           BIN 3       A          2
9           28       7/5/2015           BIN 1       B        -15
10          28       7/5/2015           BIN 3       B         15
11          28       7/5/2015           BIN 1       C        -25
12          28       7/5/2015           BIN 2       C         25
13          28       7/5/2015           BIN 1       B         50

我想通过WEEK的BIN_CODE和ITEM_NO来分组,但是从数据开始...我知道如何按周分组,但它只显示那周的摘要(不是从开始)

我期望的结果是这样的:

WEEK  BIN CODE  ITEM NO  QUANTITY
====================================
26    BIN 1     A        10 
26    BIN 1     B        20 
26    BIN 1     C        30 
26    BIN 1     D        40 
26    BIN 2     A         -   
26    BIN 2     B         -   
26    BIN 2     C         -   
26    BIN 2     D         -   
26    BIN 3     A         -   
26    BIN 3     B         -   
26    BIN 3     C         -   
26    BIN 3     D         -   
27    BIN 1     A         5 
27    BIN 1     B        20 
27    BIN 1     C        30 
27    BIN 1     D        40 
27    BIN 2     A         3 
27    BIN 2     B         -   
27    BIN 2     C         -   
27    BIN 2     D         -   
27    BIN 3     A         2 
27    BIN 3     B         -   
27    BIN 3     C         -   
27    BIN 3     D         -   
28    BIN 1     A         5 
28    BIN 1     B         55 
28    BIN 1     C         5 
28    BIN 1     D         40 
28    BIN 2     A         3 
28    BIN 2     B         -   
28    BIN 2     C         25 
28    BIN 2     D         -   
28    BIN 3     A         2 
28    BIN 3     B        15 
28    BIN 3     C         -   
28    BIN 3     D         -  

对不起我在这里写新问题..这是图片:

enter image description here

enter image description here

你能帮我吗?

之前感谢:)

2 个答案:

答案 0 :(得分:0)

尝试此查询

select Week,Registering_Date,Bin_Code,Item_No, case when asum>0 then asum else '-' end as QUANTITY
from(
select Week,Registering_Date,Bin_Code,Item_No,sum(case when Quantityfrom>0 then quentity else o end ) as asum
from tablename
group by Week,Bin_Code,Item_No)a

答案 1 :(得分:0)

希望这有效:

1A, 1B, 1C, 2A, 2B, 3A, 3B, 3C