在另一行上挑选一行

时间:2016-10-10 14:25:50

标签: sql sql-server tsql

我有一个看起来像这样的表:

ID   Type   Value
A    Z01    10
A    Z09    20
B    Z01    30
C    Z01    40
D    Z09    50
E    Z10    60

对于每个ID,我想检索一个值。理想情况下,该值应来自Z01类型的行。但是,如果Z01不可用,我会选择Z09。如果什么都没有,我想什么都不做。

结果如下:

Id   Type   Value
A    Z01    10
B    Z01    30
C    Z01    40
D    Z09    50

如何使用T-SQL完成此操作?

6 个答案:

答案 0 :(得分:3)

这可以给你你想要的东西:

select *
from table t
where 1 = case 
              when t.type = 'Z01' 
                  then 1 
              when t.type = 'Z09' 
                    and not exists (select 1 from table where id = t.id and type = 'Z01')
                  then 1 
          else 0 
       end

另一种方法是使用更常见的方法(重写CASE表达式):

select *
from table
where type = 'Z01'
    OR (type = 'Z09' and not exists (select 1 from table where id = t.id and type = 'Z01'))

一种明显的sargable方法(会使您的查询在您的表上使用适当的索引,如果它存在)将是:

select *
from table
where type = `Z01`

union all
select *

from table
where type = `Z09`
    and not exists (select 1 from table where id = t.id and type = 'Z01')

当我说索引时,我正在谈论type列上的非聚集索引。

答案 1 :(得分:0)

您可以使用此类查询

;WITH cte
AS (SELECT
    *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY type) AS rn
FROM yourtable
WHERE type IN ('Z01', 'Z09'))
SELECT
    id, type, value
FROM cte
WHERE rn = 1

答案 2 :(得分:0)

我会使用窗口函数:

select t.*
from (select t.*,
             row_number() over (partition by id
                                order by (case when type = 'Z01' then 1
                                               when type = 'Z09' then 2
                                          end)
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

我不完全理解“如果没有可用的话,那就什么也不做”。如果,你的意思是你想要'Z01','Z09',或者什么都没有,那么就这样做:

select t.*
from (select t.*,
             row_number() over (partition by id order by type) as seqnum
      from t
      where type in ('Z01', 'Z09')
     ) t
where seqnum = 1;

where子句执行过滤,您可以按字母顺序排序。

答案 3 :(得分:0)

然后试试这个

 Select distinct a.id, 
    coalesce(t1.type, t9.type) type,
    case when t1.type is not null 
         then t1.value else t9.value end value
 From table a 
    left join table t1 
       on t1.id = a.id 
          and t1.type = 'Z01'
    left join table t9 
       on t9.id = a.id 
          and t9.type = 'Z09'
  Where a.type in ('Z01', 'Z09')  -- < -- this last to eliminate row E

答案 4 :(得分:0)

这样的事情:

select distinct
base.Id,
Coalesce(z01.Type, any.Type) Type,
Coalesce(z01.Value, any.Value)
from (select distinct id from [table]) base
left outer join [table] z01
    on z01.id = base.id
    and z01.Type = 'Z01'
left outer join [table] any
    on any.id = base.id
    and any.type != 'Z01'

答案 5 :(得分:0)

WHERE子句开始。仅选择Z01和Z09的条目。然后使用ROW_NUMBER对您的行进行排名并保持最佳状态。

select id, type, value 
from
(
    select 
      id, type, value, 
      row_number() 
        over (partition by id order by case when type = 'Z01' then 1 else 2 end) as rn
    from mytable
    where type in ('Z01','Z09')
) ranked
where rn = 1;