在对其他字段进行分组时,SQL CASE和CAST一起导致聚合错误

时间:2017-11-01 16:20:30

标签: sql aggregate-functions

我有一个查询,必须将值转换为小数并除以它们。我只需要在值大于0时进行除法,否则会抛出错误。我的查询如下。由于某种原因,添加CASE语句会导致聚合错误。我已经看到了包含在SUM中的示例,但这对我的情况不起作用。有什么建议吗?

SELECT
    EmailName,
    SUM(Sent) as Sent,
    SUM(Delivered) as Delivered,
    SUM(UniqueOpens) as UniqueOpens,
    SUM(TotalOpens) as TotalOpens,
    SUM(UniqueClicks) as UniqueClicks,
    SUM(TotalClicks) as TotalClicks,
    SUM(Unsubscribes) as Unsubscribes,
    CAST(SUM(UniqueOpens) AS FLOAT)/CAST(SUM(Delivered) AS FLOAT) as OpenRate
FROM 
    [Non Triggered Sends Last Month]
GROUP BY 
    EmailName

如果UniqueOpens大于0,则此方法有效,否则

这会抛出聚合警告

SELECT
    EmailName,
    SUM(Sent) as Sent,
    SUM(Delivered) as Delivered,
    SUM(UniqueOpens) as UniqueOpens,
    SUM(TotalOpens) as TotalOpens,
    SUM(UniqueClicks) as UniqueClicks,
    SUM(TotalClicks) as TotalClicks,
    SUM(Unsubscribes) as Unsubscribes,
    CASE WHEN UniqueOpens > 0 THEN CAST(SUM(UniqueOpens) AS FLOAT)/CAST(SUM(Delivered) AS FLOAT) ELSE CAST(SUM(UniqueOpens) AS FLOAT) END as OpenRate
FROM 
    [Non Triggered Sends Last Month]
GROUP BY 
    EmailName
  

检查查询语法时发生错误。错误:列'C7211451.Non Triggered Sends Last Month.UniqueOpens'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

4 个答案:

答案 0 :(得分:0)

我认为你只需要SUM(UniqueOpens)

SELECT
EmailName,
SUM(Sent) as Sent,
SUM(Delivered) as Delivered,
SUM(UniqueOpens) as UniqueOpens,
SUM(TotalOpens) as TotalOpens,
SUM(UniqueClicks) as UniqueClicks,
SUM(TotalClicks) as TotalClicks,
SUM(Unsubscribes) as Unsubscribes,
CASE WHEN SUM(UniqueOpens) > 0 THEN CAST(SUM(UniqueOpens) AS FLOAT)/CAST(SUM(Delivered) AS FLOAT) ELSE CAST(SUM(UniqueOpens) AS FLOAT) END as OpenRate
FROM [Non Triggered Sends Last Month]
GROUP BY EmailName

答案 1 :(得分:0)

您的案例陈述也需要包含SUM。

CASE WHEN UniqueOpens > 0

需要

CASE WHEN SUM(UniqueOpens) > 0

答案 2 :(得分:0)

为什么在传递的唯一身份是非正面时,您想要一个值?我会去 SUM(UniqueOpens) * 1.0 / NULLIF(SUM(Delivered), 0) as OpenRate

 (CASE WHEN SUM(Delivered) > 0
       THEN SUM(UniqueOpens) * 1.0 / SUM(Delivered)
       ELSE 0  -- I'm assuming these SUM(Delivered) is a non-negative integer
  END) as OpenRate

但是,如果你想防止除零,我建议比较分母,而不是分子:

* 1.0

我通常使用FILE_ATTRIBUTE_SPARSE_FILE的简写来防止整数除法。转换为浮动同样好。

答案 3 :(得分:0)

在Case语句中使用sum Aggregation

SELECT
EmailName,
SUM(Sent) as Sent,
SUM(Delivered) as Delivered,
SUM(UniqueOpens) as UniqueOpens,
SUM(TotalOpens) as TotalOpens,
SUM(UniqueClicks) as UniqueClicks,
SUM(TotalClicks) as TotalClicks,
SUM(Unsubscribes) as Unsubscribes,
SUM(CASE WHEN UniqueOpens > 0 THEN 
CAST(UniqueOpens AS FLOAT)/CAST(Delivered AS FLOAT)
 ELSE CAST(UniqueOpens AS FLOAT) )END as OpenRate
FROM [Non Triggered Sends Last Month]
GROUP BY EmailName