列ごとの値を取得する必要があるSQLの問題がある(Redshift上)index
ID final_score
の最大値に基づいて列id
を入力し、この値を新しい列fav_index
に入力します。 score2
は= index n + 1
index n
は、例えば、= abc1
id
、= 0
index
及び= 10
score1
ためscore2
の値がindex
= 1
score1
の値となるとfinal_score
の値との差であるscore1
の値に等しいです。 score1
およびscore2
。Redshift - グループ化ID列Bの各IDの1つの列Aの値を別の列の最大値に基づいて取得するC
テーブルscore
を見れば簡単です。このテーブルscore
は、後で示すSQLクエリの結果です。だから、
id index score1 score2 final_score
abc1 0 10 20 10
abc1 1 20 45 25
abc1 2 45 (null) (null)
abc2 0 5 10 5
abc2 1 10 (null) (null)
abc3 0 50 30 -20
abc3 1 30 (null) (null)
、列fav_index
を含む結果のテーブルには、次のようになります。story
としてある
select
m.id,
m.index,
max(m.max) as score1,
fmt.score2,
round(fmt.score2 - max(m.max), 1) as final_score
from
(select
sv.id,
case when sv.story_number % 2 = 0 then cast(sv.story_number/2 - 1 as int) else cast(floor(sv.story_number/2) as int) end as index,
max(sv.score1)
from
story as sv
group by
sv.id,
index,
sv.score1
order by
sv.id,
index
) as m
left join
(select
sv.id,
case when sv.story_number % 2 = 0 then cast(sv.story_number/2 - 1 as int) else cast(floor(sv.story_number/2) as int) end as index,
max(score1) as score2
from
story as sv
group by
id,
index
) as fmt
on
m.id = fmt.id
and
m.index = fmt.index - 1
group by
m.id,
m.index,
fmt.score2
表:以下
id index score1 score2 final_score fav_index
abc1 0 10 20 10 0
abc1 1 20 45 25 1
abc1 2 45 (null) (null) 0
abc2 0 5 10 5 0
abc2 1 10 (null) (null) 0
abc3 0 50 30 -20 0
abc3 1 30 (null) (null) 0
は、テーブル
story
からテーブル
score
を生成するためのスクリプトです以下:
id story_number score1
abc1 1 10
abc1 2 10
abc1 3 20
abc1 4 20
abc1 5 45
abc1 6 45
私は考えることができる唯一の解決策は、何かなどを行う
select id, max(final_score) from score group by id
、その後バック(表score
を生成するために使用された)上記の長いスクリプトにそれに参加することです。私は本当に必要な情報を1列だけ追加するために、このような長いスクリプトを書くのを避けたいと思っています。
これを行うより良い方法はありますか?
ありがとうございました!
更新:mysqlの回答も受け付けます。ありがとう!
「MySQL」または「SQL Server」? – Squirrel
mysqlをタグとして削除してください/あなたのコメントを更新してください。mysqlはredshiftとは関係ありません。 –
あなたは間違っています - mysqlは普遍的な用語ではなく、赤方偏移とはかなり異なっています。この質問に対するmysqlの回答は、赤方偏移の修正を加えてもほぼ確実に機能しません。 –