在postgresql中创建视图时计算字段时出现问题
我在postgres数据库中有两个表q1data和q1lookup。q1data包含3列postid、reasonid、other,q1lookup包含2列reasonid、reason 我正在尝试创建一个视图,其中包括4列reasonid、reasons、count和percentage。count是每个原因的计数,百分比应为每个计数除以Q1数据中计数*的总和,即如果为reasonid,则为总行数 但它给出了一个错误,并表示count*附近有语法错误。下面是我正在使用的代码。请帮忙在postgresql中创建视图时计算字段时出现问题,postgresql,Postgresql,我在postgres数据库中有两个表q1data和q1lookup。q1data包含3列postid、reasonid、other,q1lookup包含2列reasonid、reason 我正在尝试创建一个视图,其中包括4列reasonid、reasons、count和percentage。count是每个原因的计数,百分比应为每个计数除以Q1数据中计数*的总和,即如果为reasonid,则为总行数 但它给出了一个错误,并表示count*附近有语法错误。下面是我正在使用的代码。请帮忙 selec
select
cwfis_web.q1data.reasonid AS reasonid,
cwfis_web.q1lookup.reason AS reason,
count(cwfis_web.q1data.reasonid) AS count,
round(
(
(
count(cwfis_web.q1data.reasonid)
/
(select count(0) AS count(*) from cwfis_web.q1data)
) * 100
)
,0) AS percentage
from
cwfis_web.q1data
join
cwfis_web.q1lookup
ON cwfis_web.q1data.reasonid = cwfis_web.q1lookup.reasonid
group by
cwfis_web.q1data.reasonid;
尝试从更改子查询
select count(0) AS count(*) from cwfis_web.q1data
到
此外,您还需要将cwfis_web.q1lookup.reason添加到分组依据中。首先,这里的语法完全无效:count0作为count*。将其替换为普通计数*,并根据原因按条目添加缺少的组,得到以下结果:
select
cwfis_web.q1data.reasonid AS reasonid,
cwfis_web.q1lookup.reason AS reason,
count(cwfis_web.q1data.reasonid) AS count,
round(
(
(
count(cwfis_web.q1data.reasonid)
/
(select count(*) from cwfis_web.q1data)
) * 100
)
,0) AS percentage
from
cwfis_web.q1data
join
cwfis_web.q1lookup
ON cwfis_web.q1data.reasonid = cwfis_web.q1lookup.reasonid
group by
cwfis_web.q1data.reasonid,
cwfis_web.q1lookup.reason;
但是,这并没有给出正确的百分比值,因为countcwfis_web.q1data.reasonid和select count*from cwfis_web.q1data都是整数类型,因此执行整数除法,结果被截断为0
如果将这些转换为预期的参数类型,则会得到以下结果:
select
cwfis_web.q1data.reasonid AS reasonid,
cwfis_web.q1lookup.reason AS reason,
count(cwfis_web.q1data.reasonid) AS count,
round(
(
(
count(cwfis_web.q1data.reasonid)::numeric
/
(select count(*) from cwfis_web.q1data)::numeric
) * 100
)
,0) AS percentage
from
cwfis_web.q1data
join
cwfis_web.q1lookup
ON cwfis_web.q1data.reasonid = cwfis_web.q1lookup.reasonid
group by
cwfis_web.q1data.reasonid,
cwfis_web.q1lookup.reason;
这部电视剧给了你更多的希望。或者,您可以将0参数强制转换为float,并将其舍入。很高兴能为您提供帮助。如果此答案解决了您的问题,请将其勾选为已接受,以便其他人看到问题已解决。
select
cwfis_web.q1data.reasonid AS reasonid,
cwfis_web.q1lookup.reason AS reason,
count(cwfis_web.q1data.reasonid) AS count,
round(
(
(
count(cwfis_web.q1data.reasonid)::numeric
/
(select count(*) from cwfis_web.q1data)::numeric
) * 100
)
,0) AS percentage
from
cwfis_web.q1data
join
cwfis_web.q1lookup
ON cwfis_web.q1data.reasonid = cwfis_web.q1lookup.reasonid
group by
cwfis_web.q1data.reasonid,
cwfis_web.q1lookup.reason;