1

我有以下查询

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
4

1 回答 1

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
于 2013-11-13T15:45:40.037 回答