选择金额总和按地点

时间:2015-08-14 13:10:07

标签: sql sql-server-2008 sum

我有两个表,一个是WeekNr和OrderNum,一个是OrderNum,Article和ammount

表一

WeekNr OrderNum
35     10001                 
35     10003
35     10008
36     10006
36     10005
37     10004
38     10007
39     10002

表2

OrderNum  Article    Ammount
10001     A           5   
10001     B           2
10002     A           2
10003     A           1
10003     B           2
10004     A           10
10005     B           1
10007     B           3

如何获得像

这样的结果
Article Total WeekNr35-36, Total WeekNr 37-38, Total WeekNr 39-40
   A         8                  10                   2
   B         5                   3                   0

2 个答案:

答案 0 :(得分:0)

您可以使用以下查询

select b.article,
      sum(case when a.weeknr in (35,36) then b.amount end ) as "Total WeekNr35-36",
      sum(case when a.weeknr in (37,38) then b.amount end ) as "Total WeekNr37-38",
      sum(case when a.weeknr in (39,40) then b.amount end ) as "Total WeekNr39-40"
      from table_one a inner join table_two b 
            on a.ordernum=b.ordernum 
      group by b.article

此处SQLFIDDLE LINK检查您的回答

答案 1 :(得分:0)

定义句点表,以便更轻松地对数据进行分组,以便在以后需要延长句点或者需要制作自定义标题时更加简单。我的建议是:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container-fluid">

    <div class="row">
      <div id="left" class="col-sm-3">
        <div class="row">
          <h1 class="col-sm-12">TEST TITLE</h1>
        </div>
      </div>
      <div id="right" class="col-sm-9">
        <nav class="row">
          <ul>
            <li class="header_sm_text col-sm-12">TEST LINK</li>
          </ul>
        </nav>
      </div>
    </div>

  </div>

然后创建一个分组数据集,使用pivot函数

进行转换
Period, PeriodText, Week
1, 'Weeks 24 and 25', 24
1, 'Weeks 24 and 25', 25

此外,我建议合并你的两个表,并将周数放入订单表。 此外,您可以插入一个运行一周功能的订单日期。