sql - 使用带有子查询的最大查询的 SQL/PL 行到列
问题描述
我使用 max 函数将行转换为列,在子查询中使用它之前,它运行良好。
情况:[请参考图片为超链接]我一共有三个问题要客户回答,他们的回答将从数据库中提取。但是,对于第一个问题,允许客户从 1 - 10 中进行选择。10 是指自由文本,将存储在 Question = 2 的答案中。
但是,我想排除客户的自由文本输入,并将提取放在列中。不得不说我将有三列:Response_1、Response_2 和 Response_3。当客户为 Question = 1 选择 10 时,Question = 3 的答案将存储在 Response_2 中,而 Question = 4 的答案将存储在 Response_3 中。
我的尝试如下:
select customer_ID
max( CASE WHEN Question = 1 THEN Answer END) Response_1,
max( CASE WHEN Question = 1 AND Answer != 10 THEN
( select
max( CASE WHEN Question = 2 THEN Answer END)
from t_question_answer)
ELSE
( select
max( CASE WHEN Question = 3 THEN Answer END)
from t_question_answer)
END)
) Response_2
from t_question_answer
group by customer_ID
当涉及到为 customer_2 提取的数据时,结果出错了,我认为在子查询中,它再次在整个数据中查找最大值,而不是指定同一个客户。
解决方案
您在条件聚合中需要更多条件逻辑:
select customer_ID
max(CASE WHEN Question = 1 THEN Answer END) Response_1,
(case when max(case when question = 1 and answer = 10 then 1 else 0 end) > 0
then max( CASE WHEN Question = 3 THEN Answer END)
else max( CASE WHEN Question = 2 THEN Answer END)
end) as Response_2,
(case when max(case when question = 1 and answer = 10 then 1 else 0 end) > 0
then max( CASE WHEN Question = 4 THEN Answer END)
else max( CASE WHEN Question = 3 THEN Answer END)
end) as Response_3
from t_question_answer
group by customer_ID
推荐阅读
- api - 彭博报告自动化
- swift - addSnapshotListener 仅获取 firebase 集合中的更改
- python - 熊猫多数据框图
- ios - 精灵卡在两个精灵之间
- scikit-learn - 在 sklearn 中训练/拟合线性回归,只有一个特征/变量
- python - 是否可以将 dash 框架与现有的 mod_python 框架或金字塔框架一起使用以在网页上部署 dash 的图形功能?
- unity-container - 将 Unity 升级到 5.11.1
- php - 如果是/否,则 PHP
- python-3.x - FastAPI 没有异步行为
- c++ - 使用 C++ 进行 HTTP2 双向流式传输