How to sum and group a table by a specific column

落花浮王杯 提交于 2020-06-17 09:38:30

问题


I have a database like this:
Question table:

QId | Title
----------
1   | SR
4   | TR
9   | AA

Answer table:

RId | QId
----------
2   | 1
3   | 1
5   | 4
6   | 4
7   | 1
8   | 4

Vote table:

PubId | Type
-------------
2     | P
3     | N
3     | N
1     | P
1     | N
5     | P
4     | P
2     | N
2     | P

I want to calculate the score of every question. The score of a question is the difference between positive and negative votes on that question and all of its answers. For example the score of question 1 (with answers as 2, 3 and 7) with QId of 1 is -1 because it hase 3 positive votes and 4 negative votes.
So far I can only calculate the score of a given question. The code is:

SELECT P+N FROM (
SELECT sum (case WHEN Type='P' then +1 else 0 end) as P,
sum (case WHEN Type='N' then -1 else 0 end) as N
from ( 
SELECT v.Type from Vote v where v.PubId in (
SELECT r.RId FROM Answer r WHERE r.QId=4
UNION
select q.QId from Question q where q.QId=4)
)
)

How can I calculate the score of every question and then sort them from the question with the highest score to the question with lowest score?

The result that I want is 4 (with the score of +2), 9 (with the score of 0), 1 (with the score of -1).


回答1:


You can use LEFT JOINs combined with CASE to compute the scores. For example:

select
  *
from (
  select
    q.qid,
    sum(case when v.type = 'P' then 1 
             when v.type = 'N' then -1 else 0 end
       ) as score
  from question q
  left join answer a on a.qid = q.qid
  left join vote v on v.pubid = a.rid
  group by q.qid
) x
order by score desc



回答2:


Hmmm . . . assuming that pubid matches rid, this is basically just conditional aggregation:

select a.qid,
       sum(type = 'P') - sum(type = 'N') as score
from answer a join
     vote v
     on v.pubid = r.rid
group by a.qid;

EDIT based on coment:

select q.qid,
       coalesce(sum(type = 'P'), 0) - coalesce(sum(type = 'N'), 0) as score
from question q left join
     answer a
     on q.qid = a.quid left join
     vote v
     on v.pubid = r.rid
group by q.qid
order by score desc;


来源:https://stackoverflow.com/questions/61988086/how-to-sum-and-group-a-table-by-a-specific-column

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!