SQL程序中的sum和sum选择并插入到

时间:2016-10-26 13:12:36

标签: sql-server tsql

我有点问题。我有插入块,选择,在内部选择我有总和。这很好用。但在这个选择中,我还需要对这些总和进行一些操作。我不知道怎么做。 代码:

insert into [dbo].[DiscountDailyStatsTemp]
    SELECT
        @DiscountId, 
        cast([dbo].[TelemetryData].[EventTime] as date) as 'Date', 
        sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountLike' then 1 else 0 end) as 'Likes',
        sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountDislike' then 1 else 0 end) as 'Dis likes',
        sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountShare' then 1 else 0 end) as 'Shares',
        SUM(case when [dbo].[TelemetryData].[EventName]='DiscountView' then 1 else 0 end) as 'Views',
        SUM(case when [dbo].[TelemetryData].[EventName]='DiscountClick' then 1 else 0 end) as 'Clicks', 
        Sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountCode' then 1 else 0 end) as 'Downloaded codes',
        Sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountSave' then 1 else 0 end) as 'Saves',
        sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountClickWWW' then 1 else 0 end) as 'Page redirections',
        0 as 'Average CTR',
        @UniqueUsers as 'Unique users',
        @NewUsers as 'New users',
        @ReturningUsers as 'Returning users',
        Sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountCommentPositive' then 1 else 0 end) as 'Positive comments',
        sum(case when [dbo].[TelemetryData].[EventName] = 'DiscountCommentNegative' then 1 else 0 end) as 'Negative comments'
    from [dbo].[TelemetryData] 
    where [dbo].[TelemetryData].[DiscountId] = @DiscountId
        and ([dbo].[TelemetryData].[EventName] = 'DiscountView' or [dbo].[TelemetryData].[EventName] = 'DiscountClick' or 
        [dbo].[TelemetryData].[EventName] = 'DiscountDislike' or [dbo].[TelemetryData].[EventName] = 'DiscountCode' or 
        [dbo].[TelemetryData].[EventName] = 'DiscountLike' or [dbo].[TelemetryData].[EventName] = 'DiscountShare' or
        [dbo].[TelemetryData].[EventName] = 'DiscountClickWWW' or [dbo].[TelemetryData].[EventName] = 'DiscountSave' or
        [dbo].[TelemetryData].[EventName] = 'DiscountCommentPositive' or [dbo].[TelemetryData].[EventName] = 'DiscountCommentNegative')
    group by cast([dbo].[TelemetryData].[EventTime] as date)
    order by cast([dbo].[TelemetryData].[EventTime] as date) asc

看看 0为'平均点击率' 我需要为此更改

Round(cast('Clicks' as float) / cast(case when 'Views' = 0 then 1 else 'Views') end as float) * 100, 2) as 'Average CTR',

但它不起作用。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您不能在创建它们的同一级别中使用别名,并且这也是具有group by子句的查询,这意味着每个列应该在group by中或者在其周围使用聚合函数。< / p>

您可以使用其他选择包装您的查询:

SELECT [date],
       [likes],
       ....
       Round(cast([Clicks] as float) / cast(case when [Views] = 0 then 1 else [Views] end) as float) * 100, 2) as [Average CTR],
FROM(YOUR QUERY HERE)

另外,使用方括号作为列名。