首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

sql分组有关问题,每天一问

2012-07-30 
sql分组问题,每天一问!这个是我写的sql语句select count(考勤天数),员工ID,月份from考勤表 group by员工ID

sql分组问题,每天一问!
 
这个是我写的sql语句
select count(考勤天数),员工ID,月份 from 考勤表 group by 员工ID,月份;

下边这个是查询出来的结果:
  考勤天数 员工ID 月份
  28 A 4
  26 A 3
  25 A 2
  28 B 3
  26 B 2
  27 C 4
  30 C 3
  27 C 2



我想让它查询出这样的显示结果怎么做呢?
  员工ID 4月 3月 2月
  A 28 26 25
  B 0 28 26
  C 27 30 27

[解决办法]

SQL code
select  员工ID,   max(case 月份 when 4 then 考勤天数 else 0 end) as 4月,   max(case 月份 when 3 then 考勤天数 else 0 end) as 3月,   max(case 月份 when 2 then 考勤天数 else 0 end) as 2月from  tbgroup by  员工ID
[解决办法]
只是月份的话 一般做法都是一个一个判断 然后合计 也可以使用存储 动态sql拼接起来
[解决办法]
SQL code
 --> 测试数据:[test]if object_id('[test]') is not null drop table [test]create table [test]([考勤天数] int,[员工ID] varchar(1),[月份] int)insert [test]select 28,'A',4 union allselect 26,'A',3 union allselect 25,'A',2 union allselect 28,'B',3 union allselect 26,'B',2 union allselect 27,'C',4 union allselect 30,'C',3 union allselect 27,'C',2--我写一个动态的declare @str varchar(2000)set @str=''select     @str=@str+',['+LTRIM([月份])+'月]=max(case when [月份]='    +ltrim([月份])+' then [考勤天数] else 0 end)'from     [test]group by    [月份]exec('select [员工ID]'+@str+' from test group by [员工ID]')/*员工ID    2月    3月    4月-------------------------------A    25    26    28B    26    28    0C    27    30    27*/ 

热点排行