SQL Server,Inner Join涉及多个where语句

时间:2014-07-14 20:34:07

标签: sql-server join

我在设置以下查询时遇到困难:

在MATERIALSCOSTACT表中查找具有两个特定MATERIALID值之一的所有WORKORDER值。

然后从WORKORDER表中我想用“主要替换”来清除所有值。或者'安装'描述然后我想确保我只看水或下水道ASSETGROUP。我想确保我只查看自今年第一年以来发生过WOMACOST的记录。

我想在其共享的WORKORDERID列上加入MATERIALSCOSTACT表和WORKORDER表。

我无法弄清楚如何在第二个语句中加入第一个语句,在第二个语句中,SQL Server在" INNER"

上给我一个语法错误
select workorderid from [CityWorks].[AZTECA].[materialcostact] where materialsid  = '30791' or 
materialsid = '30841' 


Select * from [CityWorks].[AZTECA].[WORKORDER] 
where description not like '%main replace%' and description not like '%install%'
and (assetgroup = 'WATER' or Assetgroup = 'SEWER') 
and womatcost != 0
and ACTUALSTARTDATE > '2013-12-31 00:00:00.000'
INNER JOIN workorderid on [CityWorks].[AZTECA].[materialcostact].[workorderid] =
[CityWorks].[AZTECA].[WORKORDER].[workorderid] 
group by assetgroup

非常感谢能够提供帮助的任何人!

2 个答案:

答案 0 :(得分:0)

你的where子句在错误的地方。它需要在加入之后出现。

Select * from [CityWorks].[AZTECA].[WORKORDER] 
INNER JOIN workorderid on [CityWorks].[AZTECA].[materialcostact].[workorderid] =
[CityWorks].[AZTECA].[WORKORDER].[workorderid] 
where description not like '%main replace%' and description not like '%install%'
and (assetgroup = 'WATER' or Assetgroup = 'SEWER') 
and womatcost != 0
and ACTUALSTARTDATE > '2013-12-31 00:00:00.000'
group by assetgroup

如果这些列出现在多个表中,您可能必须对表进行别名或在where子句中更明确。

答案 1 :(得分:0)

我相信这就是你想要的:

注意:尝试使用别名,它们使您的代码更易于阅读。

Select * 
from [CityWorks].[AZTECA].[WORKORDER] WO
JOIN [CityWorks].[AZTECA].[materialcostact] MC 
   on WO.[workorderid] = MC.[workorderid] 
   and (MC.materialsid = 30791 or MC.materialsid = 30841)
where description not like '%main replace%' and description not like '%install%'
and (assetgroup = 'WATER' or Assetgroup = 'SEWER') 
and womatcost != 0
and ACTUALSTARTDATE >= '2014-01-01'