【问题标题】:Filtering with priority criteria in SQL server在 SQL Server 中使用优先级条件进行过滤
【发布时间】:2020-02-04 11:57:28
【问题描述】:

我正在尝试过滤 Table1:

 Table1

 Region             mCode   pCode
 Europa               AD    E
 Rest of the world    AD    O
 East Europa          AE    O
 Outside              AE    L
 Rest of the world    AE    E
 Asia                 AF    O
 North America        AG    D
 Rest of the world    AG    L
 North America        AI    D
 Rest of the world    AI    L
 America              AI    L

pCode (D,L,E,O) 有四个不同的值,mCode 可以重复。

我只需要根据以下条件获取 mCode 具有最高优先级 pCode 的那些行:

Highest priority     pCode = D
Second priority      pCode = L 
Third priority       pCode = E 
last priority        pCode = O 

例如 mCode 'AE' 出现在 3 行中,而 pCode 是 'O'、'L' 和 'E' 在不同的行中。根据 pCode 优先级,结果显示 pCode 为第二优先级“L”的行,因为没有优先级高于“L”的“AE”行。其余的行并不重要。

所需结果将 mCode 作为唯一值:

 Region            mCode    pCode
 Europa            AD       E
 Outside           AE       L
 Asia              AF       O
 North America     AG       D
 North America     AI       D

【问题讨论】:

    标签: sql sql-server filtering


    【解决方案1】:

    您可以使用 row_number() 为每个 mCode 分配优先级,然后只过滤具有最高优先级的那个

    select *
    from
    (
        select *, p = row_number() over (partition by mCode
                                              order by case when pCode = 'D' then 1
                                                            when pCode = 'L' then 2
                                                            when pCode = 'E' then 3
                                                            when pCode = 'O' then 4
                                                            end)
        from   Table1
    ) d
    where d.p = 1
    

    【讨论】:

      【解决方案2】:

      使用窗口函数ROW_NUMBER()CASE 表达式作为

      SELECT Region, mCode, pCode
      FROM
      (
      SELECT *, 
      ROW_NUMBER() OVER(PARTITION BY mCode ORDER BY CASE pCode WHEN 'D' THEN 0
                          WHEN 'L' THEN 1
                          WHEN 'E' THEN 2
                          WHEN 'O' THEN 3
                          END) RN
      FROM
      (
        VALUES
        ('Europa'               ,'AD',    'E'),
        ('Rest of the world'    ,'AD',    'O'),
        ('East Europa'          ,'AE',    'O'),
        ('Outside'              ,'AE',    'L'),
        ('Rest of the world'    ,'AE',    'E'),
        ('Asia'                 ,'AF',    'O'),
        ('North America'        ,'AG',    'D'),
        ('Rest of the world'    ,'AG',    'L'),
        ('North America'        ,'AI',    'D'),
        ('Rest of the world'    ,'AI',    'L'),
        ('America'              ,'AI',    'L')
      ) T(Region, mCode, pCode)
      ) TT
      WHERE RN = 1;
      

      Live Demo

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多