SQL CASE输出

时间:2013-05-28 12:32:46

标签: sql

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提供了多行作为输出。为什么“All Others”小组不会成为一行呢? 2010-05所有其他278 2010-05所有其他975 2010-05所有其他223 2010-05 Internet 5124 2010-05商店19641

由于 丹

2 个答案:

答案 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;

答案 1 :(得分:0)

请参阅以下内容:

您还需要在group by子句中指定case块。

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