【问题标题】:Give priority to data from Specific Datasource优先考虑来自特定数据源的数据
【发布时间】:2015-09-23 18:48:24
【问题描述】:

我有如下数据

  ID     Name     Description                DataSource     Year
   1     Apple    Sweet & Tasty               Source_A       2016
   1     Apple    Red and Sweet & Tasty       Source_B       2015
   2     Apple    Delicious                   Source_A       2016
   2     Apple    Delicious and Red           Source_C       2015
   3     Apple                                Source_C       2013      
   3     Apple     Green and Large            Source_B       2016

就我而言,我想优先考虑 source_B,因为它更可靠。因此,如果有来自 Soure_B 的数据,我想为特定 ID 显示该行并忽略其他 ID。如果来自 source_B 的数据不存在,那么我只想显示来自其他来源的数据。另外,我想只显示一行最近的数据。

在上面的例子中,结果应该是这样的

   ID     Name     Description                DataSource    Year
   1     Apple    Red and Sweet & Tasty       Source_B      2015
   2     Apple    Delicious                   Source_A      2016
   3     Apple    Green and Large             Source_B      2016

【问题讨论】:

标签: sql-server select sql-order-by


【解决方案1】:

您可以使用 row_number + case 来确定优先级,如下所示:

select 
  id,
  name,
  description,
  datasource,
  year
from (
  select
    id,
    name,
    description,
    datasource,
    year,
    row_number () over (
      partition by ID
      order by case when DataSource = 'Source_B' then 1 else 2 end,
      Year desc
    ) as RN
  from
    table1
) X
where
  RN = 1

partition by 将为每个 ID 选择新的 ID,order by 选择行将按何种顺序获取编号。然后,外部选择会过滤掉除编号为 1 的行之外的其他行。

你可以在SQL Fiddle试试这个

【讨论】:

    【解决方案2】:

    row_number() 与自定义order by 一起使用:

    DECLARE @table TABLE(ID INT ,Name VARCHAR(30),Description VARCHAR(30),DataSource VARCHAR(30),YEAR VARCHAR(30))
    INSERT INTO @table(ID,Name,Description,DataSource,YEAR) VALUES
    (1,'Apple','Sweet & Tasty','Source_A',2016),
    (1,'Apple','Red and Sweet & Tasty','Source_B',2015),
    (2,'Apple','Delicious','Source_A',2016),
    (2,'Apple','Delicious and Red','Source_C',2015),
    (3,'Apple',NULL,'Source_C',2013),
    (3,'Apple','Green and Large','Source_B',2016)
    
    SELECT * FROM 
    (
    SELECT *,ROW_NUMBER() OVER(PARTITION BY ID ORDER BY CASE WHEN DataSource = 'Source_B' THEN 0 ELSE 1 END) rn FROM @table
    ) t
    WHERE rn = 1
    

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 2011-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多