将行聚合数据与单独的行合并
Combine row aggregate data with individual rows
我有一个 table 如下所示
base_data
session_id
event_type
player_guess
correct_answer
1
guess
'python'
NULL
1
guess
'javascript'
NULL
1
guess
'scala'
NULL
1
all_answered
NULL
['python','javascript','hadoop']
2
guess
'triangle'
NULL
2
guess
'square'
NULL
2
all_answered
NULL
['triangle','square']
我正在尝试获取一个名为 was_guess_correct
的新列,定义如下:
For each session_id, match the player_guess values with data in correct_answer. Correct answer for session_id is available when event_type = 'all_answered'
结果看起来像 -
session_id
event_type
player_guess
correct_answer
was_guess_correct
1
guess
'python'
NULL
1
1
guess
'javascript'
NULL
1
1
guess
'scala'
NULL
0
1
all_answered
NULL
['python','javascript','hadoop']
1
2
guess
'triangle'
NULL
1
2
guess
'square'
NULL
1
2
all_answered
NULL
['triangle','square']
1
行 all_answered 中的值是唯一的且已排序(可以使用顺序或仅使用 IN
子句进行检查也可能有效)
对于 event_type all_answered
的行,was_guess_correct
列无关紧要。它可以是 1 或 0 - 任何有助于使查询更容易的值。
我如何计算 SQL/ Presto 中的上述列?
我正在尝试查看 - 如何使用 JOIN/Unnest 进行计算,如果可能的话还使用内联(不使用 JOIN)进行计算。
您可以使用 window 函数来获得每一行的正确答案。那么如何管理结果取决于列的类型。如果它是一个字符串,你可以只使用 like
:
select t.*,
(case when event_type = 'all_answered' or
max(correct_answer) over (partition by session_id) like '%''' || player_guess || '''%'
then 1 else 0
end) as was_guess_correct
from t;
请注意,correct_answer
在“猜测”行中是 NULL
,因此 max()
有效(假设每个会话有一个正确答案行)。
我有一个 table 如下所示
base_data
session_id | event_type | player_guess | correct_answer |
---|---|---|---|
1 | guess | 'python' | NULL |
1 | guess | 'javascript' | NULL |
1 | guess | 'scala' | NULL |
1 | all_answered | NULL | ['python','javascript','hadoop'] |
2 | guess | 'triangle' | NULL |
2 | guess | 'square' | NULL |
2 | all_answered | NULL | ['triangle','square'] |
我正在尝试获取一个名为 was_guess_correct
的新列,定义如下:
For each session_id, match the player_guess values with data in correct_answer. Correct answer for session_id is available when event_type = 'all_answered'
结果看起来像 -
session_id | event_type | player_guess | correct_answer | was_guess_correct |
---|---|---|---|---|
1 | guess | 'python' | NULL | 1 |
1 | guess | 'javascript' | NULL | 1 |
1 | guess | 'scala' | NULL | 0 |
1 | all_answered | NULL | ['python','javascript','hadoop'] | 1 |
2 | guess | 'triangle' | NULL | 1 |
2 | guess | 'square' | NULL | 1 |
2 | all_answered | NULL | ['triangle','square'] | 1 |
行 all_answered 中的值是唯一的且已排序(可以使用顺序或仅使用 IN
子句进行检查也可能有效)
对于 event_type all_answered
的行,was_guess_correct
列无关紧要。它可以是 1 或 0 - 任何有助于使查询更容易的值。
我如何计算 SQL/ Presto 中的上述列?
我正在尝试查看 - 如何使用 JOIN/Unnest 进行计算,如果可能的话还使用内联(不使用 JOIN)进行计算。
您可以使用 window 函数来获得每一行的正确答案。那么如何管理结果取决于列的类型。如果它是一个字符串,你可以只使用 like
:
select t.*,
(case when event_type = 'all_answered' or
max(correct_answer) over (partition by session_id) like '%''' || player_guess || '''%'
then 1 else 0
end) as was_guess_correct
from t;
请注意,correct_answer
在“猜测”行中是 NULL
,因此 max()
有效(假设每个会话有一个正确答案行)。