gpt4 book ai didi

sql - 向复杂的 SQL 查询添加计数

转载 作者:行者123 更新时间:2023-12-05 01:29:37 24 4
gpt4 key购买 nike

我有以下查询返回测试问题、这些问题的可能答案以及用户选择每个可能答案的次数:

SELECT  p.program_id, 
p.pre_survey_form_id,
p.post_survey_form_id,
fq.form_id,
sq.question_id,
sq.question_text,
qo.question_option_id,
qo.option_text,
G.Total

FROM dbo.program p
LEFT OUTER JOIN dbo.form_question fq
ON p.pre_survey_form_id = fq.form_id OR p.post_survey_form_id = fq.form_id
LEFT OUTER JOIN dbo.survey_question sq
ON fq.question_id = sq.question_id
LEFT OUTER JOIN dbo.question_option qo
ON sq.question_id = qo.question_id
LEFT OUTER JOIN (
SELECT ra.question_id, ra.question_option_id, COUNT(*) AS Total
FROM dbo.form_response_answers ra
GROUP BY ra.question_option_id, ra.question_id
) G
ON G.question_id = sq.question_id AND G.question_option_id = qo.question_option_id

ORDER BY p.program_id, fq.form_id, sq.question_id, qo.question_option_id

我唯一需要做的就是对每个问题的回答数量求和,但我真的很困惑。我将计算响应的数量并获得用户选择特定响应的次数的百分比。

结果集:
----  ----  ----  --  ---------------------------------------------------------------------------  -  ------------  ----
1000 1001 1000 10 How many days a week do you drink at least eight glasses (64 oz.) of water? 1 Never 1
1000 1001 1000 10 How many days a week do you drink at least eight glasses (64 oz.) of water? 2 Once 1
1000 1001 1000 10 How many days a week do you drink at least eight glasses (64 oz.) of water? 3 Two times NULL
1000 1001 1000 10 How many days a week do you drink at least eight glasses (64 oz.) of water? 4 Three times 2
1000 1001 1000 10 How many days a week do you drink at least eight glasses (64 oz.) of water? 5 Four times NULL
1000 1001 1000 10 How many days a week do you drink at least eight glasses (64 oz.) of water? 6 Five or more NULL

最佳答案

如果我正确理解了您的模型,只需添加它即可获得问题的回答次数:

 LEFT OUTER JOIN (
SELECT ra.question_id, COUNT(*) AS TotalAnswers
FROM dbo.form_response_answers ra
GROUP BY ra.question_id
) G2

然后就像你对 G 所做的那样加入并获得 TotalAnswers。
这很简单......所以很有可能我错过了一些东西:)

关于sql - 向复杂的 SQL 查询添加计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10090006/

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