如何使用SQL将百分比添加到表中?

时间:2019-12-30 17:47:17

标签: sql-server

我正在尝试计算以下查询中Sign_Ups_with_Want_CreatedSign_Ups的百分比。我以为我可以在查询中添加一行代码来分隔sign_ups_with_want_created / sign_ups,但是运行查询时出现此错误:

  

语法错误第8:1行:无法解析“ sign_ups_with_want_created”列

代码:

select
    month(From_iso8601_timestamp(u.created)) as Month,
    count(distinct u.id) as Sign_Ups,
    count (distinct w.owner) as Sign_Ups_with_Want_Created,
    count(distinct g.owner) as Sign_Ups_with_Reel_Created,
    count(distinct 
             case 
                when g.status = 'done' then g.owner 
             end) as Sign_Ups_with_Done_Reel,
   count(distinct 
             case 
                when g.status = 'active' then g.owner 
             end) as Sign_Ups_with_Active_Reel
from
    prodjoinreel.users u
left join 
    prodjoinreel.goals g on g.owner = u.id
left join 
    prodjoinreel.wants w on w.owner = u.id
where 
    year(From_iso8601_timestamp(u.created)) = 2019
group by 
    Month
order by 
    Month

谢谢

1 个答案:

答案 0 :(得分:2)

我不认为这是基于错误消息的SQL Server,但是尝试实现此目的的一种方法是在百分比公式中再次使用列计算。根据您使用的实际引擎,您可能需要将cast()的结果count()保留为十进制,以保持除法的精度。

我使用了T-SQL语法:

select
  month(From_iso8601_timestamp(u.created)) as Month,
  count(distinct u.id) as Sign_Ups,
  count (distinct w.owner) as Sign_Ups_with_Want_Created,
  count(distinct g.owner) as Sign_Ups_with_Reel_Created,
                count(distinct 
                    case 
                    when g.status = 'done' then g.owner 
                    end
                ) as Sign_Ups_with_Done_Reel,
   count(distinct 
                    case 
                    when g.status = 'active' then g.owner 
                    end
                ) as Sign_Ups_with_Active_Reel,
   /* sign_ups_with_want_created / sign_ups */
   cast(cast(count(distinct w.owner) as decimal(19,4)) / cast(count(distinct u.id) as decimal(19,4)) as decimal(19,4)) as Pct_Sign_Ups_with_Want_Created
from
  prodjoinreel.users u
  left join prodjoinreel.goals g on g.owner = u.id
left join prodjoinreel.wants w on w.owner = u.id
where year(From_iso8601_timestamp(u.created)) = 2019
group by Month
order by Month

上面的内容很简单,但是很难维护,本质上是复制代码。在SQL Server中,还有其他选项。

另一种解决方案是使用CTE,从临时结果集中计算百分比。

另一种解决方案是将初始结果选择到临时表中;使用临时表获取最终结果;并删除临时表。