sql - Difference of 2 columns of query -
i have votequestion
table: votequestion(iduser → user, idquestion → content, isup)
and question
table: question(idquestion → content, title)
i want select 5 questions best score (upvotes-downvotes).
upvote votequestion
isup = true
, downvote votequestion
isup = false
.
i tried following query, it's not looking for. it's giving same score every question.
with upvotes ( select count(*) "a" "votequestion", "question" "votequestion"."idquestion" = "question"."idquestion" , "votequestion"."isup" true ), downvotes ( select count(*) "b" "votequestion", "question" "votequestion"."idquestion" = "question"."idquestion" , "votequestion"."isup" false ) select "title", "question"."idquestion", upvotes."a"-downvotes."b" total "votequestion", "question", upvotes, downvotes "votequestion"."idquestion" = "question"."idquestion" group "title", "question"."idquestion", upvotes."a", downvotes."b" order "total" desc limit 5
also tried this:
select "title", "question"."idquestion", ( select count(*) "votequestion", "question" "votequestion"."idquestion" = "question"."idquestion" , "votequestion"."isup" true ) upvotes, ( select count(*) "votequestion", "question" "votequestion"."idquestion" = "question"."idquestion" , "votequestion"."isup" false ) downvotes, upvotes-downvotes total "votequestion", "question" "votequestion"."idquestion" = "question"."idquestion" group "title", "question"."idquestion" order total desc limit 5
but says error: column "upvotes" not exist
how can difference of upvotes , downvotes in column query?
with conditional statement inline convert true
, false
values numbers (1 , -1 respectively) can sum votes this:
select q."title", q."idquestion", sum( case when v."isup" 1 else -1 end ) total votequestion v join question q on v."idquestion" = q."idquestion" group q."title", q."idquestion" order 3 desc limit 5
i haven't tried yet i'm pretty sure works.
edit: here's sqlfiddle runs successfully: http://sqlfiddle.com/#!15/df4ca/3
Comments
Post a Comment