0

So I am trying to use a LISTAGG function while using a WHERE statement. What I want to do is search by the WHERE statement and the LISTAGG returns a list with in relations to other columns.

In other words, when I use the WHERE statement with LISTAGG, I only get the value that I'm searching for. The other values associated with the other columns don't show up.

My script is kind of like this:

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
  • Meant to be WITH TEST AS Jan 22, 2018 at 21:44
  • 4
    Sample data and desired results would really help. Jan 22, 2018 at 21:52

2 Answers 2

1

Filter on the result of LISTAGG strikes me as a bit backwords. Generally, if you're going to aggregate several items into a list, you're doing it at the last minute, for display purposes. ideally you would filter prior to the aggregation.

The following will return one row for each location/ID that contains the specified 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
2
  • I think this would be faster than gordon's answer but I'd like the or null in the main where statement -- eg WHERE :tomatotype IS NULL OR (location, id) IN (SELECT location, id FROM tomatoland WHERE :tomatotype = tomatotype) seems the optimizer would do a better job there.
    – Hogan
    Jan 22, 2018 at 22:23
  • Ah, thank you both for your help, it's done the trick for me :) Jan 23, 2018 at 15:43
0

I think you want something like this:

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.