当前位置: 代码迷 >> Sql Server >> 求sql语句!该怎么解决
  详细解决方案

求sql语句!该怎么解决

热度:8   发布时间:2016-04-27 18:53:47.0
求sql语句!!!
ID   DATE               FLAG
------------------
A     2007-2-1       TRUE
A     2007-2-5       TRUE
A     2007-2-9       TRUE

B     2007-2-1       TRUE
B     2007-2-5       FLASE
B     2007-2-9       TRUE

要求转化成下表形式:
转化规则:某月在表中无记录,计入值   为   0,如ID   A和B   在2007年1月中无记录,所以下表1月都为0;
某月中所有值都为TRUE,则计入值   1,只要出现一次FLASE,则计入值   2  
如:
2007年2月中ID   A   的FLAG都为TRUE,所以   2月ID   A   项计入值   1,
2007年2月中ID   B   其中出现FLASE   ,所以   2月ID   B   项计入值   2,

ID     1月       2月     3月     4月
-----------------------
A       0             1     ...     ....
B       0     2     ...     ....


求sql语句!!!

------解决方案--------------------
drop table #test

create table #test (id varchar(20),[date] datetime,flag varchar(20))
insert into #test
select 'A ' , '2007-2-1 ' , 'TRUE ' union all
select 'A ' , '2007-2-5 ' , 'TRUE ' union all
select 'A ' , '2007-2-9 ' , 'TRUE ' union all

select 'b ' , '2007-2-1 ' , 'TRUE ' union all
select 'b ' , '2007-2-5 ' , 'FLASE ' union all
select 'b ' , '2007-2-9 ' , 'TRUE '


select * from #test


select id,
max(case when month([date])= '01 ' then case when flag = 'TRUE ' then 1 else 2 end else 0 end) as 一月,
max(case when month([date])= '02 ' then case when flag = 'TRUE ' then 1 else 2 end else 0 end) as 二月,
max(case when month([date])= '03 ' then case when flag = 'TRUE ' then 1 else 2 end else 0 end) as 三月
from #test group by id --(select distinct id from #test) a
  相关解决方案