开发者

Returning rows as columns

I'd love to do it as a single query, but I think it's going to require a cursor. If I can't do it as a single query, I'开发者_如何学Cd like to output the results as a SYS_REFCURSOR. A simplified example:

PRODUCT

ID   NAME         Part Number   SKU
------------------------------------
1    Widgetizer     150         1001
2    Widgetizer200  200         1002
3    WidgetizerDlx  250         1003

PRODUCT_SPEC

P_ID   NAME     VALUE
----------------------------
1      WEIGHT    5
1      HEIGHT    10
1      VERSION   1
1      COLOR     RED
2      WEIGHT    7
2      HEIGHT    10
2      VERSION   2
2      COLOR     BLUE

Query:

For each product with SKU less than 1003, return:

Product name, part #, SKU, WEIGHT, HEIGHT, COLOR


Generally referred to as a pivot query.

select p.name, p.partnum, p.sku,
       max( case when s.name='WEIGHT' then s.value else null end ) weight,
       max( case when s.name='HEIGHT' then s.value else null end ) height,
       max( case when s.name='COLOR'  then s.value else null end ) color
from product p join product_spec s on p.id = s.p_id
where sku <= 1003
group by p.name, p.partnum, p.sku
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜