1

我有以下查询来生成某些产品的 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?IE

    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) 
    

提前致谢。

4

1 回答 1

2

在 whenbook_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
于 2013-01-26T16:27:34.637 回答