将联合合并到单个查询

时间:2013-01-26 16:20:08

标签: sql oracle oracle10g

我有以下查询来生成某些产品的ID和分数

Select
  tm.product_id,
  listagg(tm.book_id || '(' || tm.score || ')',',')
    within group (order by tm.product_id) as matches
from
  tl_product_match tm 
where
  tm.book_id is not null 
group by
  tm.product_id
union 
Select
  stm.product_id,
  listagg(stm.video_id || '(' || stm.score || ')',',')
    within group (order by stm.product_id) as matches
from
  tl_product_match stm
where
  stm.video_id is not null
group by
  stm.product_id

查询产生输出,如下所示:

productId | matches
---------------------------------------------
1         | 123(30), 76565, 7687(500), 243(5)
2         | 352(30), 9(5), 34234(500), 43(5)
2         | 25(30), 78, 324(500), 23434(5)
3         | 546(30), 768, 34234(500), 324(5)

两个问题:

  • 是否可以修改查询以删除联合并仍然产生相同的结果?
  • ProductId 2重复两次(即每个联合一行),我该如何在同一行显示productId 2?即

    productId |  matches
    -----------------------------------------------------------------------------
    1         |  123(30), 76565, 7687(500), 243(5)
    2         |  352(30), 9(5), 34234(500), 43(5), 25(30), 78, 324(500), 23434(5)
    3         |  546(30), 768, 34234(500), 324(5) 
    

提前致谢。

1 个答案:

答案 0 :(得分:2)

如果book_idvideo_id具有相同的类型,您可以使用此功能:

SELECT
   product_id ,listagg(gr_id || '(' || score || ')',',') within group (order by product_id) as matches
FROM
(
    SELECT
       product_id, score, book_id gr_id
    FROM tl_product_match
    WHERE book_id is not null 
    UNION ALL
    SELECT
       product_id, score, video_id gr_id
    FROM tl_product_match
    WHERE video_id is not null
) A
GROUP BY product_id

我相信每行都包含有关图书或视频的信息。这可能有用。

SELECT
    product_id,
    listagg(COALESCE(book_id, video_id) || '(' || score || ')',',') within group (order by product_id) as matches
FROM tl_product_match
GROUP BY product_id