【问题标题】:Filter a column with specific criteria from another column in SQL Server从 SQL Server 中的另一列中筛选具有特定条件的列
【发布时间】:2019-10-07 16:36:15
【问题描述】:

我正在尝试过滤 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-server tsql filtering


【解决方案1】:

这就是我认为您正在尝试做的事情,尽管问题不是 100% 清楚:

select *

from (

  select *
       , row_number() over (
           partition by [Region] 
           order by case when [pCode] = 'D' then 1
                         when [pCode] = 'L' then 2
                         when [pCode] = 'E' then 3
                         when [pCode] = 'O' then 4
                         else 5 end) as [RN]

  from Table1
  ) sub

where [RN] = 1
and [pCode] in ('D','L','O','E')

SQL Fiddle

【讨论】:

  • 感谢您的回答。那很接近。我已经更新了我的帖子。我只需要根据以下条件获取 mCode 具有最高优先级 pCode 的那些行:最高优先级 pCode = D 第二优先级 pCode = L 第三优先级 pCode = E 最后优先级 pCode = O 例如 mCode 'AE' 出现在 3 行和 pCode是'O','L'和'E'在不同的行。根据 pCode 优先级,结果显示 pCode 为第二优先级“L”的行,因为没有优先级高于“L”的“AE”行。其余的行并不重要。
  • @SQL_NewUser 我已更新问题以限制为仅优先级中的行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-21
  • 1970-01-01
  • 2021-05-10
  • 2019-10-09
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多