用于显示列表项的SQL查询

时间:2014-08-20 11:28:01

标签: sql sql-server-2008-r2

好的,我正在尝试从糟糕的表结构中编写查询。

以下是我想要实现的目标:

表1 :项目清单

T1C1  T1C2   

  A     Fred
  B     Bart
  C     Carl

表2:第二个项目清单

T2C1  T2C2

  1     Chocolate   
  2     Cake        
  3     Pie     
  4     Fish    
  5     Pizza

表3:加入表

T3C1  T3C2   T3C3  

  1     A     Y
  4     A     Y 
  5     A     N
  1     B     N
  2     B     Y
  5     B     Y
  1     C     Y
  2     C     N
  3     C     Y

结果 根据表1中的人选择查询。 但是,如果该值不在表3中,则R1C4应默认为N

R1C1  R1C2          R1C3   R1C4

  1     Chocolate     A    Y
  2     Cake          A    N
  3     Pie           A    N
  4     Fish          A    Y
  5     Pizza         A    N

2 个答案:

答案 0 :(得分:1)

我已经假设了一些细节来提出以下内容:

DECLARE @UserId CHAR
SET @UserId = 'A'

SELECT T2.T2C1 AS R1C1,
       T2.T2C2 AS R1C2,
       COALESCE(T3.T3C2, @UserId) AS R1C3,
       COALESCE(T3.T3C3, 'N') AS R1C4
  FROM Table2 AS T2
       LEFT JOIN Table3 AS T3 ON T3.T3C1 = T2.T2C1 AND T3.T3C2 = @UserId

假设:示例输出适用于用户Fred

为确保我们看到Table2中的所有条目,我们在链接表(LEFT JOIN)上使用了Table3

我们必须COALESCE链接表中不存在的两条记录的值。

请注意,这仅适用于根据预期输出过滤给一个用户的情况。

查看我的SQL Fiddle以获取完整示例。

答案 1 :(得分:0)

declare @filter varchar(1)
select @filter= T1C1 from Table_1 where T1C2='Fred';

with CteResult (R1C1,R1C2,R1C3,R1C4)as
(select  T2C1 as R1C1,T2C2 as R1C2,T3C2 as R1C3, T3C3 as R1C4 from table_2 A
inner join Table_3 B on T2C1  =T3C1 
where T3C2=@filter)
select T2C1 as R1C1,T2C2 as R1C2,coalesce(R1C3,@filter) as R1C3,
case when R1C4 is null then 'N' else R1C4 end R1C4  
from table_2 A left outer join CteResult B
on B.R1C1=A.T2C1