2013-05-28 34 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