In my case I need to filter a file based on a ITSUser and its role.
The user can have 2 roles "A" and "B".I want only 1 File per 1 Row based on below conditions.
If
StateFile has ITSUser exists in the file and has NO role "B" then --> Yes , NoElse If
StateFile has ITSUser exists in the file and has role "B" then --> Yes , YesElse If
StateFile has NO ITSUser exists in the file and has NO role "B" then --> No , NoBelow is the query that i am using.
SELECT DISTINCT MSEF.StatefileID,
MSEF.StateFileName,
AFEE.SubmittedDate,
UNO.DisplayName AS SubmittedBy,
(select DISTINCT (
CASE WHEN (
MSETET.ITSUserID = '99'
AND ET.StateTeamName = N'Live')
THEN 'Yes'
ELSE 'No'
END)) AS CHICMAN,
(select DISTINCT (
CASE WHEN (
MSETET.ITSUserID IN( '99')
AND ET.StateTeamName IN( N'Live')
AND MSETET.StateTeamID=ET.StateTeamID ) --AND MSEF.StateFileID != MSETET.StateFileID
THEN 'Yes'
ELSE 'No'
END)) AS CHICTeamIsInTheLive
from MS.StateFile MSEF WITH (NOLOCK)
INNER JOIN EM.StateFileRem AFEE WITH (NOLOCK) ON MSEF.StateFileID = AFEE.StateFileID
INNER JOIN MS.StateTeamMember MSETM WITH (NOLOCK) ON MSETM.StateFileID=MSEF.StateFileID
INNER JOIN SOP.ITSUser UNO WITH (NOLOCK) ON AFEE.SubmittedByUserID = UNO.ITSUserID
INNER JOIN MS.StateTeamStateTeamMember MSETET ON MSETET.StateFileID=AFEE.StateFileID
INNER JOIN [MS].[StateTeam] ET WITH (NOLOCK) ON ET.StateFileID = MSETET.StateFileID
ORDER BY
MSEF.StateFileID
GO
That should work:
select top 1 with ties
StatefileID
,StateFileName
,SubmittedDate
,SubmittedBy
,CHICMAN
,CHICTeamIsInTheLive
from
(
SELECT DISTINCT MSEF.StatefileID,
MSEF.StateFileName,
AFEE.SubmittedDate,
UNO.DisplayName AS SubmittedBy,
(select DISTINCT (
CASE WHEN (
MSETET.ITSUserID = '99'
AND ET.StateTeamName = N'Live')
THEN 'Yes'
ELSE 'No'
END)) AS CHICMAN,
(select DISTINCT (
CASE WHEN (
MSETET.ITSUserID IN( '99')
AND ET.StateTeamName IN( N'Live')
AND MSETET.StateTeamID=ET.StateTeamID ) --AND MSEF.StateFileID != MSETET.StateFileID
THEN 'Yes'
ELSE 'No'
END)) AS CHICTeamIsInTheLive
from MS.StateFile MSEF WITH (NOLOCK)
INNER JOIN EM.StateFileRem AFEE WITH (NOLOCK) ON MSEF.StateFileID = AFEE.StateFileID
INNER JOIN MS.StateTeamMember MSETM WITH (NOLOCK) ON MSETM.StateFileID=MSEF.StateFileID
INNER JOIN SOP.ITSUser UNO WITH (NOLOCK) ON AFEE.SubmittedByUserID = UNO.ITSUserID
INNER JOIN MS.StateTeamStateTeamMember MSETET ON MSETET.StateFileID=AFEE.StateFileID
INNER JOIN [MS].[StateTeam] ET WITH (NOLOCK) ON ET.StateFileID = MSETET.StateFileID
) x
where CHICMAN = 'Yes' or CHICTeamIsInTheLive = 'Yes'
order by row_number() over (partition by StatefileID order by CHICMAN desc, CHICTeamIsInTheLive desc)