sql-server - 如何使用 SQL 将百分比添加到我的表中?
问题描述
我正在尝试计算下面查询中Sign_Ups_with_Want_Created
的百分比。Sign_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
谢谢
解决方案
我不认为这是基于错误消息的 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,从临时结果集中计算百分比。
另一种解决方案是将初始结果选择到临时表中;使用临时表得到最终结果;并删除临时表。
推荐阅读
- verilog - 是否可以在 Xilinx Spartan-6 FPGA 中“即时”(配置后)在单端和差分 IO 之间切换
- c# - 当我从客户端向服务器端发送对象时,内存流不可扩展
- c# - Visual stuido 2019 找不到 abd.exe
- tensorflow - tf.nn.ctc_loss 和 pytorch.nn.CTCLoss 有什么区别
- c# - 如何在组件的类中注入 DateTimeProvider / wrapper 依赖项但不使用构造函数?
- scala - Spark Dataframes 多个 JOIN
- c# - 用 C# 中的相应 html 替换多个引号标签
- bioinformatics - Snakemake 在两个不同的通配符子集上发布运行规则
- reactjs - 重新渲染组件后如何使酶预期错误
- c# - DateTime.TryParse 似乎正在丢失原始时区信息并转换为服务器时间