Microsoft SQL查询困境

时间:2017-06-15 15:10:27

标签: sql-server

我有4张桌子:

tblWorkArea (*WA, WA.Description, Unitcode*)
tblWAFileNumber (*WA, FNo, Fno.Description*)
tblElement (*WA, FNo, Tasklist, Task, Element, Code*)
tblMiscValues (*WA, FNo, FieldLabel, Datavalue*).

我需要从加入WA,FNo字段的这四个表中提取报告

(在所有表中都很常见)包含以下列:

(WA,WA.Description,FNo,Fno.Desciption,Tasklist,Task,Element,Code,Datavalue) - 其中Unitcod =' pq'和FieldLabel =' xyz'和Datavalue不应为null。

我尝试了一些连接组合,但它仍然没有拉动我需要的报告并提取重复记录。

FROM Comments:这是当前的查询:

select e.WA, w.description as WorkArea_Description
     , e.FNo
     , f.description as FileNumber_Description
     , e.tasklist
     , e.task
     , element
     , code
     , datavalue as Partnumber 
from tblElement e 
join tblworkarea w on e.WA=w.WA and 
join tblWAFileNumber f on e.WA=f.WA and e.Fno=f.FNo and 
join tblMiscValues m on e.WA=m.WA and e.FNo=m.FNo 
where UnitCode='pq' FieldLabel='xyz' 
  and DataValue not in ('Null','')

2 个答案:

答案 0 :(得分:1)

如果只需要匹配的密钥,可以使用内连接

select *
from tblWAFileNumber t1
inner join tblElement t2 on t1.WA = t2.WA and t1.FNo = t2.FNo
inner join tblMiscValues t3 on t1.WA = t3.WA and t1.FNo = t3.FNo
inner join tblWorkArea t4 on t1.WA = t4.WA
where t4.Unitcode = 'pq'
and t3.FieldLabel='xyz'
and t3.Datavalue is not null 

或如果您还需要不匹配与键相关的行

,请使用左连接
select *
from tblWAFileNumber t1
left join tblElement t2 on t1.WA = t2.WA and t1.FNo = t2.FNo
left join tblMiscValues t3 on t1.WA = t3.WA and t1.FNo = t3.FNo 
    and  t3.FieldLabel='xyz' and t3.Datavalue is not null 
left  join tblWorkArea t4 on t1.WA = t4.WA and t4.Unitcode = 'pq'

答案 1 :(得分:0)

只是解决了所提出的语法错误(重新格式化,以便我可以更快地识别语法问题。)

SELECT e.WA, w.description as WorkArea_Description
     , e.FNo
     , f.description as FileNumber_Description
     , e.tasklist
     , e.task
     , element
     , code
     , datavalue as Partnumber 
FROM tblElement e 
INNER JOIN tblworkarea w  
   on e.WA=w.WA 
-- and  had an extra and.
INNER JOIN tblWAFileNumber f 
   on e.WA=f.WA 
  and e.Fno=f.FNo --had an extra and here.
INNER JOIN tblMiscValues m 
   on e.WA=m.WA 
  and e.FNo=m.FNo 
WHERE UnitCode='pq' 
  and FieldLabel='xyz' --missing the leading and here.
  and DataValue not in ('Null','') --this just seems odd to check for null string and empty set.. I'd need to see sample data containing null string and empty set to understand what you're trying to do here.
--and DateValue <> ''  --maybe this 
--and Datevalue is not null --with this instead?

如果涉及多个表,那么完全限定元素的源表是明智的,因为我们不知道哪些值来自哪些表。因此,元素,代码,日期值需要定义源表。在select和where子句中,所有值都需要完全限定。