我编写了以下SQL查询以从该数据库中提取数据。这是我到目前为止的查询:
select network,
MAX(CASE WHEN channel = 'R' and brand ='B' and spec_ind = 'x' and extended_day_ind = 'y' then 'RB30'
WHEN channel = 'R' and brand ='G' and spec_ind = 'x' and extended_day_ind = 'Y' then 'RG90'
WHEN channel = 'R' and brand ='G' and spec_ind = 'x' and extended_day_ind = 'N' then 'RB30'
WHEN channel = 'R' and brand ='G' and spec_ind = 'x' and extended_day_ind = 'N' then 'RG30' END) as Channel,
case header
when 'Annual Shift' then value_vl end as AnnualShift,
Case header
when 'Min' then value_vl end as MinVal,
Case Header
when 'Max' then value_vl end as MaxVal
From mytable
WHERE network <> 'x'
group by network, value_vl, header
order by network asc
此查询返回如下结果:
这不是很有用,我想像这样合并这些数据:
我将如何解决此问题?谢谢!
答案 0 :(得分:1)
我认为您想要条件聚合,其表达方式如下:
select network,
(CASE WHEN channel = 'R' and brand ='B' and spec_ind = 'x' and extended_day_ind = 'y' then 'RB30'
WHEN channel = 'R' and brand ='G' and spec_ind = 'x' and extended_day_ind = 'Y' then 'RG90'
WHEN channel = 'R' and brand ='G' and spec_ind = 'x' and
extended_day_ind = 'N' then 'RB30'
WHEN channel = 'R' and brand ='G' and spec_ind = 'x' and extended_day_ind = 'N' then 'RG30'
END) as Channel,
MAX(case header when 'Annual Shift' then value_vl end) as AnnualShift,
MAX(Case header when 'Min' then value_vl end) as MinVal,
MAX(Case Header when 'Max' then value_vl end) as MaxVal
From FIN_SANDBOX.asm_paid_rates_range
WHERE network <> 'x'
group by network,
(CASE WHEN channel = 'R' and brand ='B' and spec_ind = 'x' and extended_day_ind = 'y' then 'RB30'
WHEN channel = 'R' and brand ='G' and spec_ind = 'x' and extended_day_ind = 'Y' then 'RG90'
WHEN channel = 'R' and brand ='G' and spec_ind = 'x' and
extended_day_ind = 'N' then 'RB30'
WHEN channel = 'R' and brand ='G' and spec_ind = 'x' and extended_day_ind = 'N' then 'RG30'
END)
order by network asc;
我不记得Teradata是否允许GROUP BY
中的列别名。如果这样的话,逻辑可以稍微简化一下。