表名:user_test_details
我想按照以下结果,
question_id option_a option_b option_c option_d option_e
1 0 1 0 0 1
2 2 0 0 0 0
3 0 0 1 0 1
4 0 0 2 0 0
我想要计数,option_a在question_id 1中重复多少次,如果不是则重复0次,如果是,那么根据计数。与其他选项(option_b,option_c,option_d,option_e)相同。更多声明,这里是question_id 4,option_c重复2次,结果,question_id 4,option_c值为2.
答案 0 :(得分:3)
使用条件聚合:
SELECT
question_id,
SUM(CASE WHEN option_a = 'option_a' THEN 1 ELSE 0 END) AS option_a,
SUM(CASE WHEN option_b = 'option_b' THEN 1 ELSE 0 END) AS option_b,
SUM(CASE WHEN option_c = 'option_c' THEN 1 ELSE 0 END) AS option_c,
SUM(CASE WHEN option_d = 'option_d' THEN 1 ELSE 0 END) AS option_d,
SUM(CASE WHEN option_e = 'option_e' THEN 1 ELSE 0 END) AS option_e,
FROM user_test_details
GROUP BY question_id
答案 1 :(得分:0)
select question_id,count(option_a) as option_a,count(option_b) as option_b,count(option_c) as option_c,count(option_d) as
option_d,count(option_e) option_e from user_test_details group by question_id
答案 2 :(得分:0)
尝试这样的事情。
SELECT DISTINCT question_id,
COALESCE(optA.option_a,0) as option_a,
COALESCE(optB.option_b,0) as option_b
FROM user_test_details
LEFT JOIN
(
SELECT question_id, count(option_a) as option_a FROM user_test_details
WHERE
option_a is not null or option_a <> '' group by option_a)
AS optA
ON user_test_details.question_id = optA.question_id
LEFT JOIN
(
SELECT question_id, count(option_b) as option_b FROM user_test_details
WHERE
option_b is not null or option_b <> '' group by option_b)
AS optB
ON user_test_details.question_id = optB.question_id
是的,我知道它看起来很脏。