SQL Case和Cast in Count函数

时间:2016-06-17 15:48:52

标签: sql sql-server

我只是在符合特定条件的情况下尝试从两个字段计算记录。
这个[Is it possible to specify condition in Count()?]帖子很有帮助,但它没有考虑将varchar转换为int。
这是我的代码:

SELECT Mailing_Id ,Mailing_Nm,Subject_Line,Campaign_Nm,Start_Ts,End_Ts, Mailed_Cnt, Invalid_Cnt ,Actual_Sent_Cnt ,Bounce_Cnt ,Open_Cnt ,Click_Cnt
,count(case ag.logtype when '7' then 1 end) as Unsubs
,count(case ag.category when '1' then 1 end) as Block
,count(case ag.category when '2' then 1 end) as Hard
,count(case ag.category when '3' then 1 end) as Soft
,count(case ag.category when '4' then 1 end) as Tech
,count(case ag.category when '9' then 1 end) as Unknown
  FROM [StrongMailTracking].[dbo].[SM_MAILING_SUMMARY] ms left join sm_aggregate_log ag on ms.mailing_id = ag.mailingid
  WHERE datepart(year,start_ts) = 2015 and (mailing_nm not like '%delivery report%' and mailing_nm not like '%daily helpdesk%' and mailing_nm not like '%test%')
  GROUP BY Mailing_Id ,Mailing_Nm ,Subject_Line ,Campaign_Nm ,Start_Ts ,End_Ts ,Mailed_Cnt ,Invalid_Cnt ,Actual_Sent_Cnt ,Bounce_Cnt ,Open_Cnt ,Click_Cnt
ORDER BY mailing_id asc


请注意6个案例陈述。 Logtype是int,Category是varchar。
我试过了:

  • 删除单引号
  • 添加... case cast( - as int)when ...
  • 在施放时删除单引号
  • 先铸造为数字然后再插入int 但我一直收到这个错误:“Msg 245,Level 16,State 1,Line 1 将varchar值'dynamic-preview-7179'转换为数据类型int时转换失败。“

    有没有人有关于该做什么的想法?

2 个答案:

答案 0 :(得分:1)

根据您对数据类型的描述,这应该有效:

count(case ag.logtype when 7 then 1 end) as Unsubs,
count(case ag.category when '1' then 1 end) as Block,
count(case ag.category when '2' then 1 end) as Hard,
count(case ag.category when '3' then 1 end) as Soft,
count(case ag.category when '4' then 1 end) as Tech,
count(case ag.category when '9' then 1 end) as Unknown

应将数字与数字常数进行比较;字符串到字符串常量。

虽然等效,但我会将逻辑编写为:

sum(case when ag.logtype = 7 then 1 else 0 end) as Unsubs,

为什么呢?两个原因仅仅是偏好:

  • 我更喜欢更通用的case语句,因为我发现在修改代码时,我经常需要添加新的条件。我更喜欢IN使用多个WHEN s。
  • 我更喜欢sum()而不是count()因为count(2) = count(1)

答案 1 :(得分:0)

我之前评论过,ms.Mailing_Id是一个int,ag.mailingid是一个varchar。一位同事帮我解决了这个问题:

FROM [StrongMailTracking].[dbo].[SM_MAILING_SUMMARY] ms left join sm_aggregate_log ag on CAST(ms.mailing_id As varchar(255)) = ag.mailingid

相关问题