【问题标题】:SQL CASE OutputSQL 案例输出
【发布时间】:2013-05-28 12:32:46
【问题描述】:
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 19641店

谢谢 丹

【问题讨论】:

  • 因为您是按 T_12916_VIA 分组的,它包含 'E', 'R', 'M', 'F', 'P' 的值,并且记录在这些分组上。您需要将其包装在另一个 select 语句中,然后按 via_code 分组,请参阅this example
  • 请使用更好的英语。问题很难理解。

标签: sql


【解决方案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;

【讨论】:

  • @99Valk -- np,很高兴我们能提供帮助。
【解决方案2】:

请参考以下脚本:

您还需要在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2020-08-03
    • 2014-08-06
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多