Bowling Chartの基礎としてRedshiftで表を作成しています。Redshift SQL:他の列に基づく行間計算
私はこのフォーマットに私のデータを得た:
data
:
month | product_id | kpi_type | values april | 1 | current | 330 april | 1 | target | 300 april | 2 | current | 340 april | 2 | target | 300 march | 2 | current | 270 march | 2 | target | 300
私はdiff = current-target
を挿入したいです。
私はこれを取得するために探しています:
month | product_id | kpi_type | values april | 1 | current | 330 april | 1 | target | 300 april | 1 | diff | 30 april | 2 | current | 340 april | 2 | target | 300 april | 2 | diff | 40 march | 2 | current | 270 march | 2 | target | 300 march | 2 | diff | -30
私はCTEの中で差分を計算して、元のテーブルにそれを合併することにより、そこに取得する方法を知っています。しかし、私はこれを多くの異なるvalues
とより複雑な分散公式で行いたいので、より効率的なソリューションを探しています。
ここで私が得たところです:
select a.month, a.product_id, a.values as current, b.target, a.values - b.target as diff from data a left join ( select month, product_id, values as target from data where kpi_type = 'target' ) b on md5(a.month || a.product_id) = md5(b.month || b.product_id) where kpi_type = 'current' group by 1,2,3
そこから私はそれが戻ってdata
に労働組合ができ、望ましい結果を得るが、それは効率的では見えません。
Close to this question on SQL Server。
"効率的な"ソリューションをお探しの場合は、1ヶ月+製品の組み合わせを1行保存し、現行と目標を(別々の行ではなく)列として保存する必要があります。これにより、レポート作成がはるかに簡単になります。既存の表をこの形式の別の表に変換(ETL)し、新しい表を使用して照会できます。 –
私は私のbiツールに取り込むときに、私は 'kpi_types'を仮想化目的の行として使用する必要があります。私は質問で参照されるリンクと同じフォーマットを取得しようとしています。 – tristangk