gpt4 book ai didi

sql - 3 表加入计算百分比

转载 作者:行者123 更新时间:2023-11-29 13:16:51 24 4
gpt4 key购买 nike

我有以下表格:

POLLSid | name       | colour-------------------------1  | first poll | orange2  | secon poll | blue3  | third poll | greenQUESTIONSid | poll_id | what_to_ask---------------------------1  | 1       | How nice is stackoverflow?2  | 1       | Why do you think that?3  | 2       | What do you like to eat?CHOICESid | question_id | choice_text------------------------------------1  | 1           | Very nice2  | 1           | Moderatley nice3  | 1           | Evil4  | 2           | Etc.Answersid | choice_id | poll_id | question_id--------------------------------------1  | 1         | 1       | 12  | 1         | 1       | 13  | 2         | 1       | 14  | 3         | 1       | 15  | 1         | 1       | 1

I'm trying to pull back the following:

  • A row for each choice
  • poll information appended to the row (this will duplicate, and it's ok)
  • question information appended to the row (this will duplicate, and it's ok)
  • % of each answer (from all answers for a particular poll)

My query (below) works well if there is an answer per choice, but if there is only one answer (and perhaps 3 choices), it'll only bring back one row.

How can i bring back each answer for a poll, and then the number of answers and % of answers on each choice.

SELECT Count(a.choice_id) AS answer_count,
q.what_to_ask,
c.id,
c.choice_text,
COALESCE (Count(a.choice_id) * 100.0 / NULLIF((SELECT Count(*)
FROM answers
WHERE poll_id = 2), 0), 0
) AS percentage
FROM choices c
RIGHT OUTER JOIN answers a
ON a.choice_id = c.id
INNER JOIN polls p ON p.id = a.poll_id
INNER JOIN questions q ON c.question_id = q.id
WHERE p.id = 2
GROUP BY c.id, q.what_to_ask, c.choice_text

最佳答案

我会将选择和答案之间的联接更改为 LEFT JOIN:

SELECT Count(a.choice_id) AS answer_count,
q.what_to_ask,
c.id,
c.choice_text,
COALESCE (Count(a.choice_id) * 100.0 / NULLIF((SELECT Count(*)
FROM answers
WHERE poll_id = 2), 0), 0
) AS percentage
FROM choices c
LEFT JOIN answers a
ON a.choice_id = c.id
INNER JOIN polls p ON p.id = a.poll_id
INNER JOIN questions q ON c.question_id = q.id
WHERE p.id = 2
GROUP BY c.id, q.what_to_ask, c.choice_text

在使其成为 RIGHT JOIN 时,您告诉查询仅当答案表中存在匹配项时才返回行。

关于sql - 3 表加入计算百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47842934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com