我有一个调查相关应用程序表,其中有5个问题都需要Yes(1)或No(0)答案。表格设计如下:
CREATE TABLE score (
project_id int NOT NULL,
resp_id int NULL,
q1 int,
q2 int,
q3 int,
q4 int,
q5 int,
);
示例数据:
project_id resp_id q1 q2 q3 q4 q5
1 86 1 1 1 1 1
1 114 1 1 1 1 1
1 118 0 1 1 1 0
2 154 1 1 0 1 1
2 178 1 1 1 0 1
3 182 1 0 1 1 1
3 190 1 1 1 0 1
3 208 1 1 1 1 1
3 300 1 1 1 0 0
3 329 1 1 1 1 1
我需要做的是编写一个查询,生成一个报告,我按项目ID分类,提供0个“是”答案的答复者数量(0个中的0个),1个“是”答案(1个5),2个“是”答案(5个中的2个),等等。换句话说,有多少受访者对所有问题回答“是”,对5个问题中的4个回答是,等等。
可行?任何建议表示赞赏:)
答案 0 :(得分:3)
SELECT
project_ID,
q1 + q2 + q3 + q4 + q5 AS NumYesAnswers,
COUNT(*) AS NumResponses
FROM
score
GROUP BY
project_ID, q1 + q2 + q3 + q4 + q5
修改
我会将此添加为对Lobo答案的评论,但格式化不起作用。使用PIVOT
:
SELECT
Project_ID, "0" AS NoToAll, "1", "2", "3", "4", "5"
FROM
(
SELECT Project_ID, Q1 + Q2 + Q3 + Q4 + Q5 AS NumYeses, COUNT(*) AS Answers
FROM Score
GROUP BY Project_ID, Q1 + Q2 + Q3 + Q4 + Q5
) AS X
PIVOT
(SUM(Answers) FOR NumYeses IN ("0", "1", "2", "3", "4", "5")) AS Y
答案 1 :(得分:0)
所有行业的回答乔恩都很好。此外,如果您不想重复sum语句,请使用CTE(公用表表达式)。
With
ProYes as (
select project_id,
q1 + q2 + q3 + q4 + q5 as NumYes
from score)
select project_id, NumYes, COUNT(*) as NumAnswers
from ProYes
group by project_id, NumYes
答案 2 :(得分:0)
-- Be careful about NULL fields(the following is assuming that the q* are NOT NULL fields)
SELECT project_id,
SUM(allzeroes) AS NoToAll, SUM(onlyone) AS YesToOne, SUM(two) AS YesToTwo, SUM(three) AS YesToThree, SUM(four) AS YesToFour, SUM(five) AS YesToAll
FROM (
SELECT project_id,
(CASE WHEN (q1 + q2 + q3 + q4 + q5) = 0 THEN COUNT(*) ELSE 0 END) AS allzeroes,
(CASE WHEN (q1 + q2 + q3 + q4 + q5) = 1 THEN COUNT(*) ELSE 0 END) AS onlyone,
(CASE WHEN (q1 + q2 + q3 + q4 + q5) = 2 THEN COUNT(*) ELSE 0 END) AS two,
(CASE WHEN (q1 + q2 + q3 + q4 + q5) = 3 THEN COUNT(*) ELSE 0 END) AS three,
(CASE WHEN (q1 + q2 + q3 + q4 + q5) = 4 THEN COUNT(*) ELSE 0 END) AS four,
(CASE WHEN (q1 + q2 + q3 + q4 + q5) = 5 THEN COUNT(*) ELSE 0 END) AS five
FROM score
GROUP BY project_id, (q1 + q2 + q3 + q4 + q5) ) temp_table
GROUP BY project_id
PS:请更正示例数据头;我无法编辑您的问题。谢谢!
答案 3 :(得分:-1)
创建一个存储过程并将值设置为变量,然后您可以使用sproc中的select语句并使用where子句有条件地传递它们。