mysql—如何按特定列对表进行求和和和分组

gwbalxhn  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(337)

我有这样一个数据库:
问题表:

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

答题表:

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

投票表:

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

我想计算每个问题的分数。一个问题的得分是对该问题及其所有答案投赞成票和反对票的差值。例如,qid为1的问题1(答案为2、3和7)的分数为-1,因为它有3张赞成票和4张反对票。
到目前为止,我只能计算出一个给定问题的分数。代码是:

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)
)
)

如何计算每个问题的分数,然后从分数最高的问题排序到分数最低的问题?
我想要的结果是4(分数为+2),9(分数为0),1(分数为-1)。

goqiplq2

goqiplq21#

你可以用 LEFT JOIN s与 CASE 计算分数。例如:

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
4bbkushb

4bbkushb2#

嗯。假设 pubid 比赛 rid ,这基本上只是条件聚合:

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;

基于内容编辑:

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;

相关问题