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

请教sql统计语句【换个排序方式】
表(personinformation)
字段 acceptDate(datetime) --录入时间
  admiID(nvarchar(20)) --录入人员 
  IDcardNumber(nvarchar(20))--身份证号,在这里用于统计录入个数

SQL code


  --每天,每人录入汇总
 GO
  SELECT CONVERT(varchar(100),acceptDate,23) 录入时间,admiID AS 录入人员,COUNT(IDcardNumber) AS 录入总数 
  FROM dbo.personinformation
  GROUP BY admiID,CONVERT(varchar(100),acceptDate,23)
  order by CONVERT(varchar(100),acceptDate,23) ASC




显示结果如下:

录入时间 录入人员 录入总数
2008-01-27 cq 10
2008-02-06 cq 70
2011-09-19 yml 15
2011-09-19 admin 124
2011-09-20 yml 26
2011-09-20 admin 4
2011-09-20 cq 8
2011-09-21 yml 159
.
.
.

现在我想将结果像下面这样输出:

  录入人员1 录入人员12 录入人员3 ...录入人员n(录入人员)
录入时间 数量 数量 数量 ... 数量 
录入时间 数量 数量 数量 ... 数量 
录入时间 数量 数量 数量 ... 数量 
录入时间 数量 数量 数量 ... 数量 
.
.
.

请问SQL语句要怎么写呢? 另外要说明的就是:
1、具体的某一天有可能有录入人员没有录入数据,对应的数量(0)也需要显示出来。
2、录入人员为n个,目前n=10 (最好可以是根据数据库里动态读出来而不是写死的列出来)。

谢谢

------解决方案--------------------
SQL code
declare @sql varchar(8000)
set @sql = 'select convert(varchar(10),acceptDate,120) '
select @sql = @sql + ' , sum(case admiID when ''' + admiID + ''' then 1 else 0 end) [' + admiID + ']'
from (select distinct admiID from tb) as a
set @sql = @sql + ' from tb group by convert(varchar(10),acceptDate,120)'
exec(@sql)

------解决方案--------------------
SQL code
create table personinformation(acceptDate datetime,admiID nvarchar(20),IDcardNumber nvarchar(20))
insert into personinformation select '2008-01-27','cq',' 10'
insert into personinformation select '2008-02-06','cq',' 70'
insert into personinformation select '2011-09-19','yml',' 15'
insert into personinformation select '2011-09-19','admin',' 124'
insert into personinformation select '2011-09-20','yml',' 26'
insert into personinformation select '2011-09-20','admin',' 4'
insert into personinformation select '2011-09-20','cq',' 8'
insert into personinformation select '2011-09-21','yml',' 159'
go
--select [acceptDate],[admin],[cq],[yml]from personinformation pivot (sum(1) for [admiID] in([admin],[cq],[yml]))b group by 
go
declare @s nvarchar(4000)
select @s=isnull(@s+',','')+'['+ admiID +']' from(
select distinct [admiID] from personinformation
)t
exec('select [acceptDate],'+@s+'from (select acceptdate,admiID,count(*)ct from personinformation group by acceptdate,admiID)t pivot (count([admiID]) for [admiID] in('+@s+'))b')
/*
acceptDate              admin       cq          yml
----------------------- ----------- ----------- -----------
2008-01-27 00:00:00.000 0           1           0
2008-02-06 00:00:00.000 0           1           0
2011-09-19 00:00:00.000 1           0           1
2011-09-20 00:00:00.000 1           1           1
2011-09-21 00:00:00.000 0           0           1

(5 行受影响)

*/
go
drop table personinformation