SQL连接表并显示报告的查找表数据

时间:2016-07-02 01:59:09

标签: sql sql-server join reference lookup-tables

有一个视图和另外两个我试图从中提取数据的表。创建浅色报告。有一个带有ColorID和ColorName的表,我正在尝试做的是,将dig.LightColor中的ColorName显示到LightColor0ID,LightColor1ID等列......

现在,select语句从1,2,3,4,5,6等两个表中提取数据...表LightColor引用1 =白色,2 =蓝色,3 =粉红色等...只需要实际颜色名称而不是数值。

以下是一个示例:

SELECT       
  VCT.CallInfoID
  ,DLB.LightBehaviorID
  ,VCT.Name
  ,VCT.Abbreviation
  ,VCT.Description
  ,DLB.LightColor0ID
  ,DLB.LightColor1ID 
  ,DLB.LightColor2ID
  ,DLB.LightColor3ID 
  ,DLB.LightColor4ID 
  ,DLB.LightColor5ID 
  ,DLB.LightColor6ID 
  ,DLB.LightColor7ID 
FROM V_CallInfo VCT JOIN
     LightBehavior DLB
     ON VCT.LightBehaviorID = DLB.LightBehaviorID

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您需要多次joinLightColor表格,每个name要显示一个:

SELECT       
   VCT.CallInfoID
   ,DLB.LightBehaviorID
   ,VCT.Name
   ,VCT.Abbreviation
   ,VCT.Description
   ,LC0.ColorName as Color0
   ,LC1.ColorName as Color1 
   ,LC2.ColorName as Color2
   ,LC3.ColorName as Color3
   ,LC4.ColorName as Color4
   ,LC5.ColorName as Color5
   ,LC6.ColorName as Color6
   ,LC7.ColorName as Color7
FROM V_CallInfo VCT 
   JOIN LightBehavior DLB ON VCT.LightBehaviorID = DLB.LightBehaviorID
   JOIN LightColor LC0 ON DLB.LightColor0ID = LC0.ColorID
   JOIN LightColor LC1 ON DLB.LightColor1ID = LC1.ColorID
   ...
   JOIN LightColor LC7 ON DLB.LightColor7ID = LC7.ColorID

忘了提及,如果有null个值的灯光,那么您可能需要使用outer joins代替:

LEFT JOIN LightColor...