我很难找到描述我问题的词语,因此谷歌没有提出任何结果。对不起,这可能是一个非常简单的问题。
基本上我想要有两行,这两行都是由语句之间的个别创建的。我尝试过像在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"
有什么想法?有人想指点我的任何教程吗?任何因为不知道基本问题答案的侮辱?
答案 0 :(得分: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
答案 1 :(得分:2)
听起来你需要一个案例陈述
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
答案 2 :(得分:1)
就“任何想法”而言,我建议您只研究GROUP BY子句和SQL聚合的概念。
如果您想汇总一年中的所有周,那么不想要按WEEK_ID选择或分组(您希望按年分组)