简体   繁体   中英

Need help in using LISTAGG function with DISTINCT

Select ID, 
 LISTAGG(DISTINCT VIEW_NM, ',') WITHIN GROUP(ORDER BY CAST(VISIT_PAGE_NBR as INT)) 
 AS No_Of_Views
FROM db_name.schema_name.tbl_name 
WHERE FLG_COLUMN = '0'
AND SOURCE_CD NOT IN ('1','2','3','4')
AND DATE_CR = '2022-01-01'
GROUP BY ID;

I want the VIEW_NM column values to be displayed either in ASC or DESC order. But when I do a DISTINCT VIEW_NM, I'm getting - It is not a valid ORDER BY expression. Need help in fixing this.

Also, I don't want the values of VIEW_NM column to be duplicated. Pls suggest how this can be done..

Using cte to filter out multiple VIEW_NM per ID(choosing the one with lowest VIST_PAGE_NBR):

WITH cte AS (
  SELECT ID, VIEW_NM, VISIT_PAGE_NBR::INT AS VISIT_PAGE_NBR
  FROM db_name.schema_name.tbl_name 
  WHERE FLG_COLUMN = '0'
    AND SOURCE_CD NOT IN ('1','2','3','4')
    AND DATE_CR = '2022-01-01'
  QUALIFY ROW_NUMBER() OVER(PARTITION BY ID,VIEW_NM ORDER BY VISIT_PAGE_NBR) = 1
)
SELECT ID,
    LISTAGG(VIEW_VM, ',') WITHIN GROUP(ORDER BY VISIT_PAGE_NBR) AS No_Of_Views
FROM cte
GROUP BY ID;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM