T-SQL - 基于特定值删除行

时间:2017-09-04 05:21:21

标签: sql tsql sql-server-2014

在我的情况下,我需要根据ITSUser及其角色过滤文件。

用户可以有2个角色" A"和" B"。我想根据以下条件每1行只有1个文件。

  • If StateFile的ITSUser存在于文件中,没有任何角色" B"然后 - >是的,没有
  • Else If StateFile的ITSUser存在于文件中并具有角色" B"然后 - >是的,是的
  • Else If StateFile没有ITSUser存在于文件中且没有任何角色" B"然后 - >不,不

以下是我正在使用的查询。

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 

我的当前输出: enter image description here

我的预期输出 enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

这应该有效:

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)