2013-05-28 79 views
0
select to_char(T_12895_DET_ENTERED_DATE,'yyyy-mm') as entered_date, 
CASE 
    when T_12916_VIA = 'E' then 'Internet' 
    when T_12916_VIA = 'R' then 'Store' 
    when (T_12916_VIA in ('M','F','P') or T_12916_VIA is null) then 'All Others' 
end as VIA_CODE, 
count(*) 
from cmlbrc.applicants 
where to_char(T_12895_DET_ENTERED_DATE,'yyyy') >= '2010' 
group by to_char(T_12895_DET_ENTERED_DATE,'yyyy-mm'), T_12916_VIA 
order by 1,2; 

上面的代码给了我多行作为yyyy-mm的输出。为什么不把“所有其他”组合成一行? 2010-05所有其他278 2010-05所有其他975 ​​ 2010-05所有其他223 2010-05互联网5124 2010-05商店19641SQL CASE输出

感谢 丹

+0

,因为你是'T_12916_VIA'持有的价值观'“E”,“R”,“M”,“F”的分组,“P''和它在那些记录进行分组。你需要在另一个select语句中包装这个然后通过via_code分组看看[这个例子](http://stackoverflow.com/a/1209151/1114171) –

+0

请使用更好的英语。问题很难理解。 –

回答

1

您可以将您的CASE声明您GROUP BY应删除重复的:

select to_char(T_12895_DET_ENTERED_DATE,'yyyy-mm') as entered_date, 
    CASE 
     when T_12916_VIA = 'E' then 'Internet' 
     when T_12916_VIA = 'R' then 'Store' 
     when (T_12916_VIA in ('M','F','P') or T_12916_VIA is null) then 'All Others' 
    end as VIA_CODE, 
    count(*) 
from cmlbrc.applicants 
where to_char(T_12895_DET_ENTERED_DATE,'yyyy') >= '2010' 
group by to_char(T_12895_DET_ENTERED_DATE,'yyyy-mm'), 
    CASE 
     when T_12916_VIA = 'E' then 'Internet' 
     when T_12916_VIA = 'R' then 'Store' 
     when (T_12916_VIA in ('M','F','P') or T_12916_VIA is null) then 'All Others' 
    end 
order by 1,2; 
+0

这样做。谢谢 – 99Valk

+0

@ 99Valk - np,很高兴我们可以提供帮助。 – sgeddes

0

请参考follwing脚本:

您还需要在group by子句中指定大小写块。

Create Table #Temp1(T_12895_DET_ENTERED_DATE smalldatetime,T_12916_VIA char(1)) 

insert into #Temp1 (T_12895_DET_ENTERED_DATE,T_12916_VIA) 
Select dateadd(d,id,getdate()), case When a.ID <= 10 Then 'E' 
When a.ID <= 20 Then 'R' 
When a.ID > 20 Then 'M' End 
    from Tally As a 
Where a.ID < 30 
Order by a.ID 

Select * from #Temp1 

select Year(T_12895_DET_ENTERED_DATE) as entered_date, 
CASE 
    when T_12916_VIA = 'E' then 'Internet' 
    when T_12916_VIA = 'R' then 'Store' 
    when (T_12916_VIA in ('M','F','P') or T_12916_VIA is null) then 'All Others' 
end as VIA_CODE, 
count(*) 
from #Temp1 
group by Year(T_12895_DET_ENTERED_DATE) , 
CASE 
    when T_12916_VIA = 'E' then 'Internet' 
    when T_12916_VIA = 'R' then 'Store' 
    when (T_12916_VIA in ('M','F','P') or T_12916_VIA is null) then 'All Others' 
end 
order by 1,2