3

我很难找到描述我的问题的词,所以谷歌没有找到任何结果。很抱歉(可能)是一个非常简单的问题。

基本上我想要两行,这两行都是由语句之间的个人创建的。我试过像在 Select 中一样使用“AS”语句,但这只会给我一个语法错误。

这是我的代码:

Select      WEEK_ID,
            SUM (CUR_CHARGE_UNITS) as "Pro Units"
From        DW******.SLS****
Where       (WEEK_ID Between '201201' And '201252') --Use 'as' statement here?
            Or (WEEK_ID Between '201101' And '201152')
Group By    WEEK_ID

基本上我想弄清楚如何制作

WEEK_ID Between '201201' And '201252'

折叠成一行标题为“2012”。就像我说的,我所尝试的只是

(WEEK_ID Between '201201' And '201252) As "2012"

有什么想法吗?有没有人想指点我的教程?不知道一个大概是基本问题的答案有什么侮辱吗?

4

3 回答 3

6

尝试取前 4 个字符并按其分组:

Select      LEFT(WEEK_ID,4) AS Year,
            SUM (CUR_CHARGE_UNITS) as "Pro Units"
From        DW******.SLS****
Where       (WEEK_ID Between '201201' And '201252') --Use 'as' statement here?
            Or (WEEK_ID Between '201101' And '201152')
Group By    LEFT(WEEK_ID,4)

好处是 LEFT 是 ANSI 所以应该在所有 rdbms 中工作

于 2013-01-09T17:00:08.307 回答
2

听起来你需要一个案例陈述

http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=%2Fcom.ibm.db2.doc.sqlref%2Fpsmcse.htm

select
    case when week_id between '201201' and '201252'
              then '2012'
          when week_id between '201101' and '201152'
              then '2011'
     end as 'year'
        SUM (CUR_CHARGE_UNITS) as "Pro Units"
From        DW******.SLS****
Where       (WEEK_ID Between '201201' And '201252')
        Or (WEEK_ID Between '201101' And '201152')
Group By 
     case when week_id between '201201' and '201252'
              then '2012'
          when week_id between '201101' and '201152'
              then '2011'
     end
于 2013-01-09T17:00:16.430 回答
1

就“任何想法”而言,我建议您简单地研究 GROUP BY 子句和 SQL 聚合的概念。

如果您想聚合一年中的所有周,那么您不想选择或按 WEEK_ID 分组(您希望按year分组)。

于 2013-01-09T17:03:05.590 回答