我有以下查询
SELECT orderno,
CASE WHEN param_id = 'variant' THEN param_val END AS 'variant',
CASE WHEN param_id = 'period_from' THEN param_val END AS'period_from',
CASE WHEN param_id = 'period_to' THEN param_val END AS'period_to',
CASE WHEN param_id = 'division' THEN param_val END AS 'division',
CASE WHEN param_id = 'show_div' THEN param_val END AS 'show_div',
CASE WHEN param_id = 'group_div' THEN param_val END AS 'group_div',
FROM orderreport
order by orderno
这将返回一个类似于下面的网格(为了问题的目的,我已经删除了另一些列)还有无数个订单号
orderno | variant | period_from | period_to | division | show_div | group_div
3 | AH003 | NULL | NULL | NULL | NULL | NULL
3 | NULL | 201300 | NULL | NULL | NULL | NULL
3 | NULL | NULL | 201304 | NULL | NULL | NULL
3 | NULL | NULL | NULL | SALES | NULL | NULL
3 | NULL | NULL | NULL | NULL | Y | NULL
3 | NULL | NULL | NULL | NULL | NULL | Y
我想要的输出如下,无论我尝试过什么,我都很难过。
orderno | variant | period_from | period_to | division | show_div | group_div
3| AH003 | 201300 | 201304 | SALES | Y | Y
答案 0 :(得分:5)
您的查询非常接近,我会在您的CASE表达式周围添加一个聚合函数,然后再添加一个GROUP BY:
SELECT orderno,
max(CASE WHEN param_id = 'variant' THEN param_val END) AS variant,
max(CASE WHEN param_id = 'period_from' THEN param_val END) AS period_from,
max(CASE WHEN param_id = 'period_to' THEN param_val END) AS period_to,
max(CASE WHEN param_id = 'division' THEN param_val END) AS division,
max(CASE WHEN param_id = 'show_div' THEN param_val END) AS show_div,
max(CASE WHEN param_id = 'group_div' THEN param_val END) AS group_div
FROM orderreport
group by orderno
order by orderno