2014-04-24 76 views
0

我有这样的甲骨文的SQL查询:选择两排为两列

SELECT p.item_id, c.title 
FROM product p 
JOIN category c ON (p.item_id = c.item_id) 
WHERE p.status = 'active'; 

这给我行这样的:

p.item_id | c.title 

现在,让我们说,我有另一个表标签,每行一个标签,但我知道每个产品只有两个标签。要清楚:

title      | item_id 

'Some tag'    | 1 
'Another tag'    | 1 
'Tag for another product' | 2 

我需要这样的输出:

p.item_id | c.title | t.tag_1 | t.tag_2 

因此,在这种情况下:

'Some product' | 'My category' | 'Some tag' | 'Another product' 

当我加入tag表,我不知道如何说我希望将第一个结果放入一列,然后再放入另一列。谢谢你的建议。

回答

0

因为你有两个,你可以很容易地min()max()做到这一点:

SELECT p.item_id, c.title, min(t.title) as tag1, max(t.title) as tag2 
FROM product p JOIN 
    category c 
    ON p.item_id = c.item_id JOIN 
    tags t 
    ON p.item_id = t.item_id 
WHERE p.status = 'active' 
GROUP BY p.item_id, c.title; 
0

戈登·利诺夫对你有一个很好的解决方案。 但是,如果你将有超过2,则需要更大的东西:

select item, max(title1), ..., max(titleN) from (
select item_id, 
decode(nom, 1, title, null) title1, 
.... 
decode(nom, N, title, null) titleN 
from (
select item_id, title, row_number() over (partition by item_id order by title) nom 
from category) 
) 

它,然后加入到产品,从而获得所需的输出。

如果您不仅需要在oracle中运行它,请用CASE替换解码。