日期:2014-05-18  浏览次数:20517 次

金额按年分类汇总问题?
create table tb1(id int,[date] datetime,[money] float)
insert into tb1 values(1,2010-09-01,100),
(7,2010-10-05,200),
(9,2010-12-04,150),
(3,2011-02-06,300),
(15,2011-05-07,100),
(4,2011-08-05,200),
(67,2011-08-23,140),
(11,2012-09-01,100),
(77,2012-10-05,200),
(99,2012-12-04,150),
(38,2013-02-06,300),
(107,2013-08-07,100),
(40,2014-08-05,200),
(69,2014-08-23,140);
要求:
2010-09到2011-08为一个财年y2011,2011-09到2012-08为y2012,其他类似。
并对每一个财年再进行季度划分(四个季度q1,q2,q3,q4)。
最后将每一行[date]数据进行变更,例如2011-10-05记为y2012q1,2013-08-07记为有y2013q4,其他类似。
并且插入一列num,当[money]>150,num记为1.


------解决方案--------------------
SQL code

select *
, [quarter]= case   when  9 <=DATEPART(M,date) AND DATEPART(M,date)<= 11  then 'y'+Ltrim(DATEPART(YEAR,date)+1)+'q1' 
        when  12 <=DATEPART(M,date) then  'y'+Ltrim(DATEPART(YEAR,date)+1)+'q2'
        when   DATEPART(M,date)<= 2  then 'y'+Ltrim(DATEPART(YEAR,date))+'q2' 
         when 3 <=DATEPART(M,date) AND DATEPART(M,date)<= 5  then 'y'+Ltrim(DATEPART(YEAR,date))+'q3' 
        when  6 <=DATEPART(M,date) AND DATEPART(M,date)<= 8  then 'y'+Ltrim(DATEPART(YEAR,date))+'q4' END
,[num]=case when money>150 then 1 else 0 end   from tb1