(Microsoft)SQL:有条件地从多个列中获取数据

时间:2013-06-19 14:12:54

标签: database tsql join

我刚开始使用SQL。数据存储在三个表中。下面给出一个例子......

TABLE1 :ProductFamily

column: product family

TABLE2 :设施

column: location

TABLE3 :表带

column: build plant
column: prod series
column: 2012 Full Units w/C
column: 2013 Full Units w/C
column: 2014 Full Units w/C
column: 2015 Full Units w/C
column: 2016 Full Units w/C
column: 2017 Full Units w/C
column: 2018 Full Units w/C

如果...存储在“location”中的任何文本值与“building plant”中的给定文本值匹配&如果存储在“产品系列”中的任何文本值与“产品类型”

中的给定文本值匹配

然后......在相应的行中抓取七列“201X Full Units w / C:”的内容,并构建一个由它们组成的新表及其匹配的“location”和“product family”值。

我的查询:

select facility.location, ProductFamily.productfamily, strap.[2012 Full Units w/C], [2013 Full Units w/C],  strap.[2014 Full Units w/C],  strap.[2015 Full Units w/C], [2016 Full Units w/C], strap.[2017 Full Units w/C], strap.[2018 Full Units w/C]
from facility, ProductFamily
inner join strap on ProductFamily.productfamily = strap.[prod series]
inner join facility on strap.[build plant] = facility.location;

我不确定查询是否会实现我想要的还会出现语法错误(缺少运算符)

1 个答案:

答案 0 :(得分:2)

我认为你的问题在这里:

from facility, ProductFamily

我会写这样的查询:

select F.location, P.productfamily, S.[2012 Full Units w/C],
    S.[2013 Full Units w/C],  S.[2014 Full Units w/C], S.[2015 Full Units w/C], 
    S.[2016 Full Units w/C], S.[2017 Full Units w/C], S.[2018 Full Units w/C]
from strap S
inner join ProductFamily P on S.[prod series] = P.productfamily
inner join facility F on S.[build plant] = F.location;

(我不喜欢表和列名称中的空格)