展平的SQL查询

时间:2016-08-19 15:03:45

标签: sql sql-server

这是在SQL Server 2014中。

在不更改表格结构的情况下,您可以建议更改此查询的最简单方法(输出如下所示)

select 
    a.Id, a.Sku, a.lbl,
    Desc, 
    (select b.Valu where b.Attribute = 'rel') as 'rel',
    (select b.Valu where b.Attribute = 'uom') as 'uom',
    (select b.Valu where b.Attribute = 'clas') as 'clas'
from 
    items a 
join
    itemattributes b on b.id = a.id

输出:

id  sku     lbl          desc   rel     uom     clas
2   X111    X111-456789  red    NULL    NULL    C
2   X111    X111-456789  red    NULL    Cs      NULL
2   X111    X111-456789  red    3       NULL    NULL
3   X222    X222-567890  white  NULL    NULL    B
3   X222    X222-567890  white  NULL    Cs      NULL
3   X222    X222-567890  white  2       NULL    NULL
4   X333    X333-678901  blue   NULL    NULL    C
4   X333    X333-678901  blue   NULL    Ea      NULL
4   X333    X333-678901  blue   9       NULL    NULL

到此输出:

id  sku     lbl          desc   rel     uom     clas
2   X111    X111-456789  red    3       Cs      C
3   X222    X222-567890  white  2       Cs      B
4   X333    X333-678901  blue   9       Ea      C

3 个答案:

答案 0 :(得分:3)

您可以使用条件聚合按不同的属性值进行分组。

{{1}}

答案 1 :(得分:3)

你可以尝试:

select a.Id 
    , a.Sku
    , a.lbl
    , Desc
    , rel.Valu as  'rel'
    , uom.Valu as 'uom'
    , clas.Valu as 'clas'
from items a    
join itemattributes rel   
    on rel.id = a.id and rel.Attribute = 'rel'
join itemattributes uom  
    on uom.id = a.id and uom.Attribute = 'uom'
join itemattributes clas   
    on clas.id = a.id  and clas.Attribute = 'clas'

这假设您只需要包含所有三个值的记录。如果这不是一个真正的假设,请尝试左连接。注意我将属性放在连接中,以便在必须使用左连接时更容易。如果您使用内部联接,那么您可以将它们放在where子句中。

答案 2 :(得分:1)

你可以做多个连接:

select a.Id 
    , a.Sku
    , a.lbl
    , Desc
    , b.Valu as 'rel'
    , c.Valu as 'uom'
    , d.Valu as 'clas' 
from items a        
    join itemattributes b on b.id = a.id    
    join itemattributes c on c.id = a.id    
    join itemattributes d on d.id = a.id 
where b.Attribute = 'rel'   
   and c.Attribute = 'uom'  
   and d.Attribute = 'clas'

您还应该能够完全消除连接:

select a.Id 
    , a.Sku
    , a.lbl
    , Desc
    , (select b.Valu from itemattributes b where b.id = a.id and b.Attribute = 'rel') as 'rel'
    , (select b.Valu from itemattributes b where b.id = a.id and b.Attribute = 'uom') as 'uom'
    , (select b.Valu from itemattributes b where b.id = a.id and b.Attribute = 'clas') as 'clas'
from items a