SQL查询表,每个ID有多行,每个ID输出一行

时间:2015-01-10 00:16:06

标签: sql sql-server

这对我来说有点头疼。我简化了表格,并添加了一个示例场景来协助上下文。我需要在SQL Server中编写一个查询,它将使用第一个表中的数据通过中心的引用表输出第三个表中的结果。我不是非常聪明地编写SQL查询(但肯定会变得更好),所以你能提供给我的任何帮助都会很棒!表格如下:

下面是可能包含的数据表 单个身份的一个和三个条目。

┌────────┬──────────────────┐
│Identity│Partial_Identifier│
├────────┼──────────────────┤
│100     │a                 │
├────────┼──────────────────┤
│100     │b                 │
├────────┼──────────────────┤
│100     │c                 │
├────────┼──────────────────┤
│101     │b                 │
├────────┼──────────────────┤
│102     │b                 │
├────────┼──────────────────┤
│102     │c                 │
└────────┴──────────────────┘

下面是一个参考表,它与部分标识符组合相匹配 到显示目的所需的单个(唯一)IDCode。设计是 不是我认为理想的东西,但那是预先存在的,所以 我必须用它来做。

┌──────┬────────────────────┬────────────────────┬────────────────────┐
│IDCode│Partial_Identifier_1│Partial_Identifier_2│Partial_Identifier_3│
├──────┼────────────────────┼────────────────────┼────────────────────┤
│1     │a                   │                    │                    │
├──────┼────────────────────┼────────────────────┼────────────────────┤
│2     │a                   │b                   │                    │
├──────┼────────────────────┼────────────────────┼────────────────────┤
│3     │a                   │b                   │c                   │
├──────┼────────────────────┼────────────────────┼────────────────────┤
│4     │b                   │                    │                    │
├──────┼────────────────────┼────────────────────┼────────────────────┤
│5     │b                   │c                   │                    │
├──────┼────────────────────┼────────────────────┼────────────────────┤
│6     │b                   │c                   │d                   │
└──────┴────────────────────┴────────────────────┴────────────────────┘

对于第一个表中的数据,我希望得到以下结果:

┌────────┬──────┐
│Identity│IDCode│
├────────┼──────┤
│100     │3     │
├────────┼──────┤
│101     │4     │
├────────┼──────┤
│102     │5     │
└────────┴──────┘

非常感谢您提供的关于如何处理这种愚蠢行为的任何帮助。

1 个答案:

答案 0 :(得分:1)

可能不是最有效的方式,但这可行:

declare @a table (id int, p_id nchar(1))
insert @a
select 100,'a'
union select 100,'b'
union select 100,'c'
union select 101,'b'
union select 102,'b'
union select 102,'c'

declare @b table (idcode int, p_id1 nchar(1), p_id2 nchar(1), p_id3 nchar(1))
insert @b
select 1, 'a', null, null
union select 2, 'a', 'b', null
union select 3, 'a', 'b', 'c'
union select 4, 'b', null, null
union select 5, 'b', 'c', null
union select 6, 'b', 'c', 'd'

select id, idcode
from 
(
    select id
    , max(case when r=1 then p_id end) a
    , max(case when r=2 then p_id end) b
    , max(case when r=3 then p_id end) c
    from (
        select id, p_id, row_number() over (partition by id order by p_id) r
        from @a
    ) x
    group by id
) y
inner join @b b
on coalesce(b.p_id1,'') = coalesce(y.a,'')
and coalesce(b.p_id2,'') = coalesce(y.b,'')
and coalesce(b.p_id3,'') = coalesce(y.c,'')
order by id
相关问题