如何一起使用LISTAGG和WHERE

时间:2018-01-22 21:43:55

标签: sql oracle where-clause listagg

所以我在使用LISTAGG语句时尝试使用WHERE函数。 我想要做的是搜索WHERE语句,LISTAGG返回与其他列关系的列表。

换句话说,当我将WHERE语句与LISTAGG一起使用时,我只会获得我正在搜索的值。与其他列关联的其他值不会显示。

我的脚本有点像这样:

WITH TEST AS 
  (
  SELECT DISTINCT
         LOCATION,
         ID,
         LISTAGG (TOMATOCOUNT, ', ') 
             WITHIN GROUP (ORDER BY TOMATOCOUNT) 
             OVER (PARTITION BY LOCATION, ID) TOMATOTYPES,

  FROM TOMATOLAND
  )

SELECT
*
FROM TEST
WHERE (:TOMATOTYPE = TOMATO
    OR :TOMATOTYPE IS NULL)

2 个答案:

答案 0 :(得分:1)

LISTAGG的结果进行过滤会让我感到有些偏僻。通常,如果您要将多个项目聚合到一个列表中,那么您将在最后一刻将其用于显示目的。理想情况下,您将在聚合之前进行过滤。

以下内容将为包含指定location的每个ID / tomatotype返回一行。

SELECT DISTINCT
       location,
       id,
       LISTAGG (tomatotype, ', ')
           WITHIN GROUP (ORDER BY tomatocount)
           OVER (PARTITION BY location, id)
           tomatotypes
FROM   tomatoland
WHERE  (location, id) IN (SELECT location, id
                          FROM   tomatoland
                          WHERE  :tomatotype = tomatotype)
       OR  :tomatotype IS NULL

答案 1 :(得分:0)

我想你想要这样的东西:

WITH TEST AS (
      SELECT LOCATION, ID,
             LISTAGG(TOMATOTYPE, ', ') WITHIN GROUP (ORDER BY TOMATOCOUNT) OVER (PARTITION BY LOCATION, ID) as TOMATOTYPES
      FROM TOMATOLAND
     )
SELECT *
FROM TEST
WHERE ', ' || :TOMATOTYPE || ', ' LIKE '%,' || TOMATOTYPES || ', %' OR
      :TOMATOTYPE IS NULL