Trouble in calculating the field while creating view in postgresql -


i have 2 tables q1data , q1lookup in postgres database. q1data contains 3 columns (postid, reasonid, other) , q1lookup contains 2 columns (reasonid, reason).

i trying create view include 4 columns (reasonid, reason, count, percentage). count count of each reason , percentage should each count divided total of count(*) q1data (i.e. total rows if reasonid).

but gives error , says syntax error near count(*). following code using. please help.

select       cwfis_web.q1data.reasonid reasonid,      cwfis_web.q1lookup.reason reason,      count(cwfis_web.q1data.reasonid) count,      round(         (             (                 count(cwfis_web.q1data.reasonid)                  /                  (select count(0) count(*) cwfis_web.q1data)             ) * 100         )      ,0) percentage        cwfis_web.q1data  join       cwfis_web.q1lookup       on cwfis_web.q1data.reasonid = cwfis_web.q1lookup.reasonid  group       cwfis_web.q1data.reasonid; 

firstly, have invalid piece of syntax there: count(0) count(*). replacing plain count(*), , adding missing group by entry reason, gives this:

select       cwfis_web.q1data.reasonid reasonid,      cwfis_web.q1lookup.reason reason,      count(cwfis_web.q1data.reasonid) count,      round(         (             (                 count(cwfis_web.q1data.reasonid)                  /                  (select count(*) cwfis_web.q1data)             ) * 100         )      ,0) percentage        cwfis_web.q1data  join       cwfis_web.q1lookup       on cwfis_web.q1data.reasonid = cwfis_web.q1lookup.reasonid  group       cwfis_web.q1data.reasonid,      cwfis_web.q1lookup.reason; 

however, as live demo shows doesn't give right value percentage, because count(cwfis_web.q1data.reasonid) , (select count(*) cwfis_web.q1data) both of type integer, integer division performed, , result truncated 0.

if cast these numeric (the expected argument type of the 2-parameter round() function, this:

select       cwfis_web.q1data.reasonid reasonid,      cwfis_web.q1lookup.reason reason,      count(cwfis_web.q1data.reasonid) count,      round(         (             (                 count(cwfis_web.q1data.reasonid)::numeric                 /                  (select count(*) cwfis_web.q1data)::numeric             ) * 100         )      ,0) percentage        cwfis_web.q1data  join       cwfis_web.q1lookup       on cwfis_web.q1data.reasonid = cwfis_web.q1lookup.reasonid  group       cwfis_web.q1data.reasonid,      cwfis_web.q1lookup.reason; 

which this live demo shows gives more hoping for. (alternatively, can cast float, , lose ,0 argument round(), as in demo.)


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -