2016-08-19 64 views
0

这是SQL Server 2014平顶SQL查询

在不改变表的结构是什么,你可以建议修改此查询(如下图所示输出)最简单的方法

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 
+0

根据表格和索引的大小,我会使用HLGEM的解决方案(下面)进行最佳优化。 –

+0

谢谢你们。所有伟大的投入。我倾向于发现自己写这种方式约翰P.显示。但VKP让我想起我之前做过的事情。我有时会想,多个连接会在哪里开始对我产生影响。 – Steve

回答

3

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

select a.Id 
    , a.Sku 
    , a.lbl 
    , [Desc] 
    , max(case when b.Attribute = 'rel' then b.Valu end) as rel 
    , max(case when b.Attribute = 'uom' then b.Valu end) as uom 
    , max(case when b.Attribute = 'clas' then b.Valu end) as clas 
from items a  
join itemattributes b 
    on b.id = a.id 
group by a.Id 
    , a.Sku 
    , a.lbl 
    , [Desc] 
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 
+0

@vkp显示了另一个不错的选择>> GROUP BY –

+1

绝对的个人偏好我会将WHERE条件放在Join子句中以提高查询意图的可读性,因为HLGEM提到能够轻松地将此切换为左连接,假设某个属性类型不见了。 – Matt

+0

@matt是的。 HLGEM给出了这个例子。六种方式之一,另一种是六种。 –

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子句中。