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

怎么用SQL语句实现本月至本日累计数据(在线等)???
现有表BZCL:
DH                                 CL
0701-101                     10
0701-201                     12
0702-101                     11
0702-201                     11
0703-101                     12
0703-201                     12.5
0704-101                     13
0704-201                     14
  。。。
说明:DH:   0701-101代表7月1日101班的数据
0701-201代表7月1日201班的数据
其它数据类推

想得到的合计数据如下:
班组               当日产量           本月至本日累计      
101       13                         46
201                   14                         49.5

用SQL语句怎么实现?


------解决方案--------------------
--改一下

create table #BZCL( DH varchar(100), CL money)
insert into #BZCL

select '0701-101 ',10 union all
select '0701-201 ',12 union all
select '0702-101 ',11 union all
select '0702-201 ',11 union all
select '0703-101 ',12 union all
select '0703-201 ',12.5 union all
select '0704-101 ',13 union all
select '0704-201 ',14


--定义本日变量
declare @本日 varchar(100)

set @本日= '0704 '

select right(DH,3),sum(case when left(DH,4)=@本日 then CL else 0 end) as 当日产量,sum(case when left(DH,2)=left(@本日,2) then CL else 0 end) as 本月至本日累计
from #BZCL as T
group by right(DH,3)

drop table #BZCL
------解决方案--------------------
declare @a table(DH varchar(10), CL float)
insert @a select '0701-101 ', 10
union all select '0701-201 ', 12
union all select '0702-101 ', 11
union all select '0702-201 ', 11
union all select '0703-101 ', 12
union all select '0703-201 ', 12.5
union all select '0704-101 ', 13
union all select '0704-201 ', 14

select 班组=right(dh,3),
当日产量=sum(case when left(dh,4)=right(convert(varchar(6),getdate(),12),4) then cl else 0 end),
本月至本日累计=sum(case when left(dh,4) between right( '00 '+ltrim(month(getdate())),2)+ '01 ' and right(convert(varchar(6),getdate(),12),4) then cl else 0 end)
from @a group by right(dh,3)


------解决方案--------------------
Select
Right(DH, 3) As 班组,
SUM(Case When DateDiff(dd, RQ, GetDate()) = 0 Then CL Else 0 End) As 当日产量,
SUM(Case When DateDiff(dd, RQ, GetDate()) = 0 Then 1 Else 0 End) As 当日件数,
SUM(Case When DateDiff(mm, RQ, GetDate()) = 0 And RQ <= GetDate() Then CL Else 0 End) As 本月至本日累计
From
BZCL
Group By
Right(DH, 3)