return 1 row from multiple case statements - sql-server

In the following Query below in the port with the case statements I'm trying to figure out how to not return a null value when the SegmentType doesn't match.
QRSubscriberTag,MLKSubscriberTag, QTMSubscriber Tag, are actually a table of Tags uniquely identified by their SegID and a segmentType associated to the SegID. I use an outer apply with a subquery that calls FOR XML PATH('') to concatenate the Tags together related to the specific tag.
The flaw with this method is that when the Tag isn't for example QRSubscriberTag, then a null record in the QRSubscriberTag column is created.
QRSubscriberTag|QR01|MLKSubscriberTag|MLK01|QTMSubscriberTag|QTM01|QTM02
NULL |NULL|NULL |{Data}|null |FH |45
TKP ;OCP ;OCR ;|R |NULL |null |null |null |null
What I would like to see is all the Data in 1 line
QRSubscriberTag|QR01|MLKSubscriberTag|MLK01|QTMSubscriberTag|QTM01|QTM02
TKP ;OCP ;OCR ;|R |NULL |{Data}|null |FH |45
Below is my code
SET NOCOUNT ON
USE [Apps]
SELECT [BusRuleEnforceID], [FormatType], [Format],
[tag], [TagValue], Operator,
[QRSubscriberTag],[QR01],
[MLKSubscriberTag],[MLK01],
[QTMSubscriberTag],[QTM01],[QTM02]
FROM
(
SELECT
DISTINCT main.BusRuleEnforceID,
main.FormatType,
main.Format,
main.tag,
main.TagValue,
main.Operator,
CASE
WHEN seg.SegmentType = 'QR' THEN LEFT(SegsubscriberTags.list, LEN(SegsubscriberTags.list))
END AS [QRSubscriberTag],
CASE
WHEN seg.SegmentType = 'MLK' THEN LEFT(SegsubscriberTags.list, LEN(SegsubscriberTags.list)-1)
END AS [MLKSubscriberTag],
CASE
WHEN seg.SegmentType = 'QTM' THEN LEFT(SegsubscriberTags.list, LEN(SegsubscriberTags.list)-1)
END AS [QTMSubscriberTag],
c.ItemName as [SegmentId],
Case
WHEN c.ItemValue is not null and len(rtrim(c.ItemValue)) > 0 THEN c.ItemValue
ELSE LEFT(TagOptions.list, LEN(TagOptions.list)-1)
END as [Tags]
FROM
BMT_BusRulemaineria main
LEFT OUTER JOIN
BMT_BusRuleServiceType st
ON st.MappingmaineriaID = main.BusRuleEnforceID
LEFT OUTER JOIN
BMT_BusRuleSegment seg
ON seg.BusRuleEnforceID = main.BusRuleEnforceID
LEFT OUTER JOIN
BMT_BusRuleItem c
ON c.BusRuleEnforceSegID = seg.BusRuleEnforceSegID
LEFT OUTER JOIN
BMT_BusRuleItemOption co
ON c.BusRuleItemId = co.BusRuleItemId
OUTER APPLY
(
SELECT
IsNull(co2.Tag, '{Unknown}') + ISNULL('=' + co2.TagValue, '') + ':' + IsNull(co2.ItemValue, '')+ ';' AS [text()]
FROM
BMT_BusRuleItemOption co2
WHERE
co.BusRuleItemId = co2.BusRuleItemId
ORDER BY
co2.BusRuleItemId
FOR XML PATH('')
) TagOptions (list)
OUTER APPLY
(
SELECT
IsNull(porttag.Tag, '{Unknown}') + ' ' + ISNULL(porttag.Operator, '') + ' ' + IsNull(porttag.TagValue, '') + ';' AS [text()]
FROM
BMT_BusRuleSegmentTag porttag
WHERE
seg.BusRuleEnforceSegID = porttag.BusRuleEnforceSegID
ORDER BY
porttag.BusRuleEnforceSegID
FOR XML PATH('')
) SegsubscriberTags (list)
WHERE main.BusRuleEnforceID = 632563
AND main.TagTypeId = 1
) AS QRSourceTable
PIVOT
(
max([Tags])
FOR [SegmentId] IN ([QR01], [MLK01], [QTM01], [QTM02])
) AS QRPivotTable
ORDER BY
[TagTypeId], [BusRuleEnforceID]
EDIT: Full Result Set
Note: QRSubscriber, MLKSubscriber, and QTMSubscriber tags all have unique SegIDs.
<table><tbody><tr><th>FormatType</th><th>Format</th><th>Version</th><th>AmtCode</th><th>Date</th><th>LocationIdentifier</th><th>TagType</th><th>tag</th><th>TagValue</th><th>Operator</th><th>InfoCode</th><th>QRSubscriberTag</th><th>QR01</th><th>QR02</th><th>QR03</th><th>QR04</th><th>QR05</th><th>QR06</th><th>QR07</th><th>MLKSubscriberTag</th><th>MLK01</th><th>QTMSubscriberTag</th><th>QTM01</th><th>QTM02</th></tr><tr><td>DN</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td><td>TIR</td><td>RPSAMN</td><td>NULL</td><td>exists</td><td>78</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td><td>{Data}</td><td>NULL</td><td>TRH</td><td>675</td></tr><tr><td>DN</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td><td>TIR</td><td>RPSAMN</td><td>NULL</td><td>exists</td><td>78</td><td>TKRARAP not exists TKRALAP not exists TKRADAP not exists </td><td>J</td><td>SKU</td><td>34</td><td>NULL</td><td>NULL</td><td>SILMULTU:2;SILMHLTU:67</td><td>TOPALD:{Data};QORITK{Data}</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td><td>NULL</td></tr></tbody></table>

Use the ELSE clause to assign a default value when the comparison does not match, like so:
CASE WHEN port.SegmentType = 'QR' THEN
LEFT(SegDependantTags.list, LEN(SegDependantTags.list))
ELSE 'Your Value Rather Than NULL Goes Here'
END AS [QRSubscriberTag],

It seems that instead of using Distinct in your QRSourceTable sub-query you want to use a Group By with a MAX aggregate function on your subscriber tag fields:
SELECT
main.BusRuleEnforceID,
main.FormatType,
main.Format,
main.tag,
main.TagValue,
main.Operator,
max(CASE
WHEN port.SegmentType = 'QR' THEN LEFT(SegDependantTags.list, LEN(SegDependantTags.list))
END) AS [QRSubscriberTag],
max(CASE
WHEN port.SegmentType = 'MLK' THEN LEFT(SegDependantTags.list, LEN(SegDependantTags.list)-1)
END) AS [MLKSubscriberTag],
max(CASE
WHEN port.SegmentType = 'QTM' THEN LEFT(SegDependantTags.list, LEN(SegDependantTags.list)-1)
END) AS [QTMSubscriberTag],
c.ItemName as [SegmentId],
Case
WHEN c.ItemValue is not null and len(rtrim(c.ItemValue)) > 0 THEN c.ItemValue
ELSE LEFT(TagOptions.list, LEN(TagOptions.list)-1)
END as [Tags]
from
...
WHERE main.BusRuleEnforceID = 632563
AND main.TagTypeId = 1
GROUP BY main.BusRuleEnforceID,
main.FormatType,
main.Format,
main.tag,
main.TagValue,
main.Operator

Related

UDTF Error- SQL compilation error: Unsupported subquery type cannot be evaluated

I created a User-Defined table function that translates part numbers for our company. Part numbers are 15-19 digit alphanumeric strings that give us different information about each product. A common comparison would be an Automotive VIN number. The one key difference is that, over the years, the structure of these numbers has changed. So, one year the color might be characters 11 & 12, and the next it might be 15 & 16. In addition, codes might have different meanings for different years. For instance, the code "BL" might be blue for one year, but the next it could be light blue. It's not ideal, but it's the hand I have been dealt. To decode the part numbers, I created a User Defined Table Function. The logic for this originally existed in MS SQL. It has procedural logic, but that is not allowed in UDTFs in Snowflake. So, I got creative and rewrote the function using CTEs. It is complicated because I have one table that identifies the structure of the part number, and another table that can match the codes to get the matching description based on any dependencies.
The UDTF runs successfully when I hardcode a value:
SELECT * FROM TABLE(fDecodeSmartNumber('A19GELEXXXXGRGG'));
It also runs successfully if I join it with a table, but no values are returned:
SELECT sr.Company, sr.RMANum, sr.OrderNumber, d.FieldValue
FROM
tRMADataFinal sr
JOIN
table(fDecodeSmartNumber(sr.PartNumber)) d
WHERE
OrderNUmber IS NOT NULL AND
WAVLine IS NULL AND
Make IS NULL AND
FieldName = 'Make' AND
FieldValue IS NOT NULL
However, if I add fields to the RMA data that would not be filtered by the where clause, it errors.
I am curious if this is the same error seen here:
https://docs.snowflake.com/en/sql-reference/udf-table-functions.html
However, I do not think that workaround will work for me because I need multiple join conditions in the "on" clause of my left join in the function.
Full function code:
CREATE OR REPLACE FUNCTION fDecodePartNumber
(
vPartNumber varchar
)
RETURNS TABLE
(
Code VARCHAR(25),
FieldName VARCHAR(200),
FieldValue VARCHAR(200)
)
AS
$$
with SNValues as (
SELECT
FieldName,
SUBSTRING(vPartNumber,Position,Length) as SNValue
FROM
SmartDecodeParts
WHERE
SNFormat = (SELECT CASE WHEN SUBSTRING(vPartNumber,2,2) >= 18 THEN '2018' ELSE '2017' END)
),
FirstResultSet as (
SELECT
V.SNValue as Code, V.FieldName, K.Dsc, K.Dependency, K.Dvalue
FROM
SNValues V
LEFT JOIN
SmartDecodeKeys K
ON
V.SNValue = K.Code AND
V.FieldName = K.FieldName
),
extColor as (
SELECT
N.Code,
REPLACE(N.FieldName,' ','') as FieldName,
Color,
STANDARD_COLOR,
C.Dependency,
C.DValue
FROM
FirstResultSet N
INNER JOIN
ColorTranslation C
ON
N.Code = C.SMART_CODE
INNER JOIN
FirstResultSet R
ON
R.Dsc = C.STANDARD_MAKE
WHERE
N.FieldName = 'Ext Color'
),
intColor as (
SELECT
N.Code,
Replace(N.FieldName,' ','') as FieldName,
Color,
STANDARD_COLOR,
C.Dependency,
C.DValue
FROM
FirstResultSet N
INNER JOIN
ColorTranslationInterior C
ON
N.Code = LEFT(C.SMART_CODE,(SELECT Length FROM SmartDecodeParts WHERE FieldName = 'Int Color' AND SNFormat = (SELECT CASE WHEN SUBSTRING(vPartNumber,2,2) >= 18 THEN '2018' ELSE '2017' END)))
INNER JOIN
FirstResultSet R
ON
R.Dsc = C.STANDARD_MAKE
WHERE
N.FieldName = 'Int Color'
),
seatColor as (
SELECT
N.Code,
REPLACE(N.FieldName,' ','') as FieldName,
Color,
STANDARD_COLOR,
C.Dependency,
C.DValue
FROM
FirstResultSet N
INNER JOIN
ColorTranslationSeat C
ON
N.Code = C.SMART_CODE
INNER JOIN
FirstResultSet R
ON
R.Dsc = C.STANDARD_MAKE
WHERE
N.FieldName = 'Seat Color'
),
NormalizedResult as (
SELECT * FROM FirstResultSet
UNION ALL
Select Code, FieldName, Color, Dependency, DValue FROM extColor
UNION ALL
SELECT Code, 'StdExtColor', STANDARD_COLOR, Dependency, DValue FROM extColor
UNION ALL
Select Code, FieldName, Color, Dependency, DValue FROM intColor
UNION ALL
SELECT Code, 'StdIntColor', STANDARD_COLOR, Dependency, DValue FROM intColor
UNION ALL
Select Code, FieldName, Color, Dependency, DValue FROM seatColor
UNION ALL
SELECT Code, 'StdSeatColor', STANDARD_COLOR, Dependency, DValue FROM seatColor
),
NormalizedWithDependencies as (
SELECT
Code, FieldName, Dsc, Dependency, m.value::string as DValue
FROM
NormalizedResult,
lateral flatten(input=>split(DValue, ',')) m
UNION ALL
SELECT
*
FROM
NormalizedResult
WHERE
DValue IS NULL
)
SELECT
D.Code,
REPLACE(D.FieldName,' ',''),
D.Dsc
FROM
NormalizedWithDependencies D
LEFT JOIN
NormalizedWithDependencies R
ON
CASE WHEN LEFT(D.DValue,1) = '!' AND SUBSTRING(D.DValue,2,LEN(R.DValue)-1) <> R.Code THEN 1
WHEN LEFT(D.DValue,1) <> '!' AND D.DValue = R.Code THEN 1
ELSE 0 END = 1 AND
D.Dependency = R.FieldName
LEFT JOIN
NormalizedWithDependencies R2
ON
CASE WHEN LEFT(R.DValue,1) = '!' AND SUBSTRING(R.DValue,2,LEN(R.DValue)-1) <> R2.Code THEN 1
WHEN LEFT(R.DValue,1) <> '!' AND R.DValue = R2.Code THEN 1
ELSE 0 END = 1 AND
R.Dependency = R2.FieldName
WHERE
(D.Dependency IS NULL OR
(R.Code IS NOT NULL AND R.Dependency IS NULL) OR
(R.Code IS NOT NULL AND R2.Code IS NOT NULL)) AND
D.FieldName <> 'Ext Color' AND
D.FieldName <> 'Int Color' AND
D.FieldName <> 'Seat Color'
$$
;
Any ideas?
You are joining a table function which probably should be a user defined function not a UDTF as you should only get one decoding per VIN.
But anyways the function turns into a correlated subquery which Snowflake does not support, thus the error message.

Join Results in duplication

I have two tables. I suppose to get the result into one row, but when i try with the below query it results duplication.
Query:
Select OrgaID, UnitID, LeaveTitle, NoOfFromService, NoOfToService,
EmpType.EmployeeTypeName, IsExpatriate,
(ALR.LeaveTypeShortName + '(' + convert(varchar,ALR.NoofDays) + ') | ' +
MLR.LeaveTypeShortName + '(' + convert(varchar,MLR.NoofDays) + ') | ')
Leaves
From LeaveCategory LvCat
Left Join (Select LeaveCategoryID, LeaveTypeShortName, NoofDays From
LeaveEntitledEntry Where LeaveTypeShortName = 'AL' ) ALR On
ALR.LeaveCategoryId = LvCat.Id
Left Join (Select LeaveCategoryID, LeaveTypeShortName, NoofDays From
LeaveEntitledEntry Where LeaveTypeShortName = 'MDL' ) MLR On
ALR.LeaveCategoryId = LvCat.Id
Where OrgaID = #OrgaID and LvCat.Status = 1
For Reference :
Table 1: (LeaveCategory)
Table 2: (LeaveEntitledEntry)
Result :
So how can i change my joins to achieve expected result. Any help appreciated. Thanks in advance
You can try using conditional aggregation to access the two types of leave data by using a join to a single subquery. The reason this trick might work is that allows us to generate a single record for each LeaveCategoryID, along with its NoofDays values for both the AL and MDL types. This means that we can do with just a single join, which should avoid the duplication problem you were having.
WITH cte AS (
SELECT
LeaveCategoryID,
MAX(CASE WHEN LeaveTypeShortName = 'AL' THEN NoofDays END) AS NoofDaysAL,
MAX(CASE WHEN LeaveTypeShortName = 'MDL' THEN NoofDays END) AS NoofDaysMDL
FROM LeaveEntitledEntry
GROUP BY LeaveCategoryID
)
SELECT
OrgaID,
UnitID,
LeaveTitle,
NoOfFromService,
NoOfToService,
EmpType.EmployeeTypeName,
IsExpatriate,
'AL(' + CONVERT(varchar, t.NoofDaysAL) + ') | ' +
'MDL(' + CONVERT(varchar, t. NoofDaysMDL) + ') | ') AS Leaves
FROM LeaveCategory LvCat
LEFT JOIN cte t
ON LvCat.Id = t.LeaveCategoryID
WHERE
OrgaID = #OrgaID AND
LvCat.Status = 1;

Updating multiple columns for each record from table with multiple records for each ID

This is my first time posting a question here so please be gentle, I searched as exhaustively as I could. Sometimes it's how to search for the answer that is half the battle.
What I'm trying to do is update Table 1 with the data from Table 2 for each person for each period. Some people will have category A,B, and/or C records in Table 2, but not all and not necessarily all three.
The problem I'm running into is that my statement I'm using to do the update will update some of the columns but not all. I'm guessing this is because the updates weren't committed yet while doing the update so it can't fetch values that haven't been committed yet.
Do I need to do 3 separate update statements or can this somehow be handled through a case statement. I'm looking for most efficient methods here. Updating Table 1 who has 2 million records for each period.
Table 1 - Period_Perf
CustID
Period_Date
Perf_Cat_A
Perf_Cat_B
Perf_Cat_C
Table 2 - Period_Perf_Detail
CustID
Period_Date
Perf_Category (will contain A, B, or C)
Perf_Points (will contain a integer value)
Here's essentially the statement I've been trying to use:
UPDATE
Period_Perf
SET
Perf_Cat_A = CASE WHEN pd.Perf_Category = 'A' then pd.Total_Perf_Points else Perf_Cat_A END
Perf_Cat_B = CASE WHEN pd.Perf_Category = 'B' then pd.Total_Perf_Points else Perf_Cat_B END
Perf_Cat_C = CASE WHEN pd.Perf_Category = 'C' then pd.Total_Perf_Points else Perf_Cat_C END
from
Period_Perf
ON
INNER JOIN
(
select
CustID
,Period_Date
,Perf_Category
,sum(Perf_Points) as Total_Perf_Points
from
Period_Perf_Detail
group by CustID, Period_Date, Perf_Category
) as pd
ON
Period_Perf.CustID = pd.CustID and Period_Perf.Period_Date = pd.Period_Date
To update all the values at once, you'll need to have data that has all those three values in one row, so something like this:
UPDATE P
SET
Perf_Cat_A = pd.Cat_A,
Perf_Cat_B = pd.Cat_B,
Perf_Cat_C = pd.Cat_C
from
Period_Perf P
cross apply (
select
sum(case when Perf_Category = 'A' then Perf_Points else 0 end) as Cat_A,
sum(case when Perf_Category = 'B' then Perf_Points else 0 end) as Cat_B,
sum(case when Perf_Category = 'C' then Perf_Points else 0 end) as Cat_C
from
Period_Perf_Detail D
where
D.CustID = P.CustID and
D.Period_Date = P.Period_Date
) as pd
I haven't tested this, but hopefully there's no bugs.
Use SELECT statements first to understand your data, then build an update based on that select statement.
First use the following query to better understand why your update statement is not producing your desired results.
SELECT CASE WHEN pd.Perf_Category = 'A' THEN pd.Total_Perf_Points ELSE Perf_Cat_A END AS Perf_Cat_A
, CASE WHEN pd.Perf_Category = 'B' THEN pd.Total_Perf_Points ELSE Perf_Cat_B END AS Perf_Cat_B
, CASE WHEN pd.Perf_Category = 'C' THEN pd.Total_Perf_Points ELSE Perf_Cat_C END AS Perf_Cat_C
FROM Period_Perf
ON
INNER JOIN
(
SELECT CustID
, Period_Date
, Perf_Category
, SUM(Perf_Points) AS Total_Perf_Points
FROM Period_Perf_Detail
GROUP BY CustID
, Period_Date
, Perf_Category ) AS pd
ON Period_Perf.CustID = pd.CustID
AND Period_Perf.Period_Date = pd.Period_Date
I suggest the following query for your update.
UPDATE Period_Perf
SET Perf_Cat_A = SUM(a.Perf_Points)
, Perf_Cat_B = SUM(b.Perf_Points)
, Perf_Cat_C = SUM(c.Perf_Points)
FROM Period_Perf
LEFT JOIN Period_Perf_Detail AS a
ON Period_Perf.CustID = a.CustID
AND Period_Perf.Period_Date = a.Period_Date
AND a.Perf_Category = 'A'
LEFT JOIN Period_Perf_Detail AS b
ON Period_Perf.CustID = b.CustID
AND Period_Perf.Period_Date = b.Period_Date
AND a.Perf_Category = 'B'
LEFT JOIN Period_Perf_Detail AS c
ON Period_Perf.CustID = c.CustID
AND Period_Perf.Period_Date = c.Period_Date
AND a.Perf_Category = 'C'
GROUP BY Period_Perf.CustID , Period_Perf.Period_Date
Please notice that instead putting criteria in a WHERE, it is in the join itself. This way you don't affect the entire dataset, but just the subsets individually on each join.

TSQL Group By & Count not aggregating as expected

I have a query that returns 6 rows and I want to aggregate the information to provide a single row with a count of instances. The without aggregate query returns the correct data but when I add a GroupBy and Count to the query it returns 2 rows.
The underlying ID (SR01.ReportKey) shown in the first result has two records so I think the Group By is somehow using this field in the grouping.
NOTE: The ReportKey is not actually used in the query I just had it in the first result for information purposes.
Question :
Any idea why the Group By is not grouping all the rows into a single result with a count of 6?
Without aggregate
Query :
SELECT
'Open' AS RecStatus,
ISNULL(UWZone.UWZoneID,'') AS ZoneID,
ISNULL(UWZone.UWZoneName,'') AS ZoneName,
Branch.BranchID,
ISNULL(Branch.BranchName,'') AS BranchName,
UW.UWID AS ServicingRep,
ISNULL(UW.UWName,'') + '/' + ISNULL(UA.UWName, '') AS RepName
FROM ProductivityRecommendations
INNER JOIN SR01 ON SR01.ReportKey = ProductivityRecommendations.ReportKey
LEFT JOIN UW ON SR01.Underwriter = UW.UWID
LEFT JOIN UW AS UA ON SR01.UA = UA.UWID
LEFT JOIN Branch ON SR01.ProdBranch = Branch.BranchID
LEFT JOIN UWZone ON UWZone.UWZoneAbbrev = Branch.UWZone
WHERE ISNULL(SR01.ServicingBranch,'-') <> '-'
AND ProductivityRecommendations.DateComplete BETWEEN #DateFrom AND #DateTo
AND ProductivityRecommendations.RecCriticality IN ('CRI', 'CCM')
AND ProductivityRecommendations.RecStatus IN ('N','O','U','A','R')
AND DateRecIssued IS NOT NULL
AND (#Zone IS NULL OR (UWZone.UWZoneID IN (SELECT val FROM ufn_SplitMax(#Zone ,','))))
AND (#Branch IS NULL OR (Branch.BranchID IN (SELECT val FROM ufn_SplitMax(#Branch ,','))))
AND (#RepID IS NULL OR (SR01.Underwriter IN(SELECT val FROM ufn_SplitMax(#RepID ,','))) OR #RepID IS NULL OR (SR01.UA IN(SELECT val FROM ufn_SplitMax(#RepID ,','))))
AND (#InsuredNumber IS NULL OR (ProductivityRecommendations.CustNum IN (SELECT val FROM ufn_SplitMax(#InsuredNumber ,','))))
Results :
Adding aggregates
Query :
SELECT
'Open' AS RecStatus,
ISNULL(UWZone.UWZoneID,'') AS ZoneID,
ISNULL(UWZone.UWZoneName,'') AS ZoneName,
Branch.BranchID,
ISNULL(Branch.BranchName,'') AS BranchName,
UW.UWID AS ServicingRep,
ISNULL(UW.UWName,'') + '/' + ISNULL(UA.UWName, '') AS RepName,
COUNT(ProductivityRecommendations.RecStatus) AS Requests
FROM ProductivityRecommendations
INNER JOIN SR01 ON SR01.ReportKey = ProductivityRecommendations.ReportKey
LEFT JOIN UW ON SR01.Underwriter = UW.UWID
LEFT JOIN UW AS UA ON SR01.UA = UA.UWID
LEFT JOIN Branch ON SR01.ProdBranch = Branch.BranchID
LEFT JOIN UWZone ON UWZone.UWZoneAbbrev = Branch.UWZone
WHERE ISNULL(SR01.ServicingBranch,'-') <> '-'
AND ProductivityRecommendations.DateComplete BETWEEN #DateFrom AND #DateTo
AND ProductivityRecommendations.RecCriticality IN ('CRI', 'CCM')
AND ProductivityRecommendations.RecStatus IN ('N','O','U','A','R')
AND DateRecIssued IS NOT NULL
AND (#Zone IS NULL OR (UWZone.UWZoneID IN (SELECT val FROM ufn_SplitMax(#Zone ,','))))
AND (#Branch IS NULL OR (Branch.BranchID IN (SELECT val FROM ufn_SplitMax(#Branch ,','))))
AND (#RepID IS NULL OR (SR01.Underwriter IN(SELECT val FROM ufn_SplitMax(#RepID ,','))) OR #RepID IS NULL OR (SR01.UA IN(SELECT val FROM ufn_SplitMax(#RepID ,','))))
AND (#InsuredNumber IS NULL OR (ProductivityRecommendations.CustNum IN (SELECT val FROM ufn_SplitMax(#InsuredNumber ,','))))
GROUP BY UWZone.UWZoneID, UWZone.UWZoneName, Branch.BranchID, Branch.BranchName, SR01.ServicingRep, UW.UWID, ISNULL(UW.UWName,'') + '/' + ISNULL(UA.UWName, '')
Results :
as #Johan said in a comment:
This will should give you 1 row only in your described senario:
GROUP BY
ISNULL(UWZone.UWZoneID,''),
ISNULL(UWZone.UWZoneName,''),
Branch.BranchID,
ISNULL(Branch.BranchName,'') ,
UW.UWID,
ISNULL(UW.UWName,''),
ISNULL(UA.UWName, '')
Try a "select distinct" of the columns that you are grouping by, and also a LEN to see if they have spaces or other char that are not seen, and also test for NULLs. Then, you decide how to handel these columns, using ISNULL, COALESCE, CASE, and/or WHERE statements, depending on what you need.

SQL Server - How to remove repeating 2nd column

I have query that is similar to the following and wish to remove the repeating rows in the second/third column...need examples where I can use the following (top 1, max, min, etc...) or other best method without using derived query to remove the duplicate values. Thanks JK
WITH cteEMPAssistants (executive_personnel_number, assistant_personnel_number, assistant_type, SecType) AS
(SELECT DISTINCT CASE
WHEN ISNUMERIC(KA.KIT_asgn_emplid) = 1 THEN CAST(CAST(KA.KIT_asgn_emplid AS INT) AS VARCHAR(11))
ELSE ''
END AS executive_personnel_number ,
CAST(CAST(KAP.emplid AS INT) AS VARCHAR(11)) AS assistant_personnel_number ,
ISNULL(LATT1.xlatlongname, '') AS assistant_type ,
CAST(LATT1.fieldvalue AS VARCHAR(4)) AS SecType ,
ISNULL(LATT3.xlatshortname, '') AS assign_role
FROM dbo.KIT_ASGN_PRNT AS KAP
LEFT OUTER JOIN dbo.KIT_ASSIGNMENTS AS KA ON KA.emplid = KAP.emplid
AND KA.effdt = KAP.effdt
LEFT OUTER JOIN dbo.KIT_EMPLOYEES AS EXECT ON EXECT.EMPLID = KA.KIT_ASGN_EMPLID
LEFT OUTER JOIN dbo.KIT_EMPLOYEES AS ASST ON ASST.EMPLID = KAP.EMPLID
LEFT OUTER JOIN dbo.XLATITEM AS LATT1 ON LATT1.fieldname = 'KIT_ASGN_TYPE'
AND LATT1.fieldvalue = KAP.KIT_asgn_type
LEFT OUTER JOIN dbo.XLATITEM AS LATT3 ON LATT3.fieldname = 'KIT_ASGN_ROLE'
AND LATT3.fieldvalue = KA.KIT_asgn_role
AND LATT3.xlatshortname = 'Primary'
WHERE KAP.effdt =
(SELECT MAX(effdt)
FROM dbo.KIT_ASGN_PRNT
WHERE emplid = KAP.emplid
AND effdt <= GETDATE() ) --Return data only when employee and assistant active; null is for temps
AND (EXECT.EMP_STATUS = 'A'
OR EXECT.EMP_STATUS IS NULL )
AND ASST.EMP_STATUS = 'A' --Return all floating secretaries
AND (KAP.KIT_asgn_type = 'F' --Return all assigned secretaries, who are assigned to a person and not a task
OR (KAP.KIT_asgn_type IN ('A',
'AF')
AND KA.KIT_asgn_person = 'Y' ) ) )
SELECT CAST(EMP.KIT_EMPLID AS VARCHAR(15)) AS employeeNumber ,
KAP.emplid AS Assistant ,
SECRES.SecType AS SecType
FROM dbo.KIT_EMPLOYEES AS EMP
LEFT OUTER JOIN cteEMPAssistants AS SECRES ON EMP.KIT_EMPLID = SECRES.assistant_personnel_number
WHERE (EMP.EMP_STATUS = 'A')
AND (EMP.PER_ORG IN ('EMP',
'CWR'))
AND (ISNULL(EMP.KIT_NETWORK_ID, '') <> '')
Here is sample output:
employeeNumber Assistant SecType
--------------- --------- -----------------
1234 1112 A
1234 1112 A
1234 1112 A
1234 1112 A
4567 1113 NULL
1278 1114 NULL
1365 1115 NULL
1298 1116 A
1476 1117 A
1191 1118 NULL
You should be able to append this to the end of your query:
GROUP BY EMP.KIT_EMPLID, KAP.emplid, SECRES.SecType

Resources