日期:2014-05-19  浏览次数:20552 次

复杂的统计!!
原数据:
日期             品牌   规格     产品条码
2006-1-1     A           Z         000001
2006-1-1     A           Z         000002
2006-1-1     B           Z         000003
...               ...       ...         ...
要求统计格式为:根据选择的日期段(比如2006-1-1至2006-1-31)统计产品的数量:
品牌       规格       2006-1-1       2006-1-2       2006-1-3     ...   2006-1-31


------解决方案--------------------
少条件了

declare @sql varchar(8000)
set @sql= ' '
select @sql=@sql+ ',[ '+convert(varchar(10),日期,120)+ ']=sum(case when convert(varchar(10),日期,120)= ' ' '+convert(varchar(10),日期,120)+ ' ' ' then 1 else 0 end) '
from tablename
where 日期> = '2006-1-1 ' and 日期 < '2006-2-1 '
group by convert(varchar(10),日期,120)

exec( 'select 品牌,规格 '+@sql+ ' from tablename where 日期> = ' '2006-1-1 ' ' and 日期 < ' '2006-2-1 ' ' group by 品牌,规格 ')


------解决方案--------------------
--如果日期是Varchar,並且每天都有數據的話

Declare @StartDate Varchar(10), @EndDate Varchar(10)
Select @StartDate = '2006-1-1 ', @EndDate = '2006-1-31 '
Declare @S Nvarchar(4000)
Select @S = N 'Select 品牌, 规格 '
Select @S = @S + ' , SUM(Case 日期 When ' ' ' + 日期 + ' ' ' Then 1 Else 0 End) As [ ' + 日期 + '] '
From TableName Where 日期 Between @StartDate And @EndDate Group By 日期
Select @S = @S + ' From TableName 日期 Between ' ' ' + @StartDate + ' ' ' And ' ' ' + @EndDate + ' ' ' Group By 品牌, 规格 '
EXEC(@S)
------解决方案--------------------
declare @t table(日期 varchar(10),品牌 varchar(10),规格 varchar(10),产品条码 varchar(10))
insert into @t select '2006-1-1 ', 'A ', 'Z ', '000001 '
union all select '2006-1-1 ', 'A ', 'Z ', '000002 '
union all select '2006-1-1 ', 'B ', 'Z ', '000003 '

select * from @t
pivot
(count(产品条码)
for 日期 in ([2006-1-1],[2006-1-2],[2006-1-3])
) as pit

/*

品牌 规格 2006-1-1 2006-1-2 2006-1-3
---------- ---------- ----------- ----------- -----------
A Z 2 0 0
B Z 1 0 0

(2 行受影响)
*/
------解决方案--------------------
if not object_id(N 'tb ') is null
drop table tb
go

create table tb(日期 datetime ,品牌 char(1),规格 char(1))
go

insert into tb select convert(varchar(10),getdate(),120), 'A ', 'Z '
union all
select convert(varchar(10),getdate(),120), 'A ', 'Z '
union all
select convert(varchar(10),getdate()+1,120), 'B ', 'Z '
union all
select convert(varchar(10),getdate(),120), 'B ', 'Z '

select * from tb

--执行查询
declare @Sql varchar(2000),
@BeginDate datetime,
@EndDate datetime,
@CurrDate datetime

select @BeginDate = getdate(), @EndDate = getdate()+10, @CurrDate = @BeginDate