Combine rows in Teradata SQL if a id field appears more than once

33 views Asked by At

I'm trying to go from the first picture to the second picture. Basically, if the Concatenated field appears more than once do to there being 2 or more reps attached to the identifier, show all the names in a new column, if there is only one rep then return that one name

My initial query:

SELECT
NA.SoldToNbr
, NA.DivCd
, NA.Mgmt_Rep_Nm
, concat(NA.SoldToNbr,' ',NA.DivCd) RepIdConcat
FROM NA
WHERE NA.SlsOrgCd = 1000000
AND NA.MgmtRepNbr <>  00000000
AND NA.Mgmt_Rep_Nm not like '(AGENCY%'
AND NA.Mgmt_Rep_Nm not like '(DEADWOOD%'
AND NA.Mgmt_Rep_Nm not like '(CPTS%'
AND NA.Mgmt_Rep_Nm not like '(TEMP%'
GROUP BY 1,2,3,4

Is there a way to do this in Teradata SQL? Pictures are attached here: Sample return for initial query Desired end result

I've tried using XMLAGG but keep getting the storage limit exceeded error

SELECT DISTINCT
NA.Sold_To_Desc
, NA.DivCd
, NA.Mgmt_Rep_Nm
, concat(NA.ShipToNbr,' ',NA.DivCd) RepIdConcat
,    CASE
        WHEN COUNT(RepIdConcat) > 1 THEN TRIM(TRAILING ',' FROM TRIM(TRAILING ' ' FROM (XMLAGG(TRIM(NA.Mgmt_Rep_Nm) ORDER BY NA.Mgmt_Rep_Nm) (VARCHAR(10)))))
        ELSE MAX(NA.Mgmt_Rep_Nm)
    END AS CombinedRepValues
FROM NA
WHERE NA.SlsOrgCd = 1000
AND NA.MgmtRepNbr <>  00000000
AND NA.Mgmt_Rep_Nm not like '(AGENCY%'
AND NA.Mgmt_Rep_Nm not like '(DEADWOOD%'
AND NA.Mgmt_Rep_Nm not like '(CPTS%'
AND NA.Mgmt_Rep_Nm not like '(TEMP%'
GROUP BY 1,2,3,4;
0

There are 0 answers