2016-05-18 3 views
1

これで新しいので、任意のヒントがありがとう!SQL - 一般的な列のないテーブルの結合

私は以下のクエリを持っています。私が必要とするデータの最後のビットはCONTACT.DATUSを持ち込むことです。問題は、CONTACTテーブルには、私がすでに使用しているテーブルと共通するものは何もないことです。私はテーブルSO - > CUSTOMER - > CONTACTから行くことでそれらをリンクすることができますが、それが可能なのかどうか私は少しも考えていません。あなたは最後の参加でこれをやろうとしているところを見ることができますが、これはうまくいきません。

お手数をおかけしていただきありがとうございます。

Select DISTINCT 
so.num AS Ref 
, so.shiptoname AS Recipient_Full_Name 
, so.shiptoaddress AS Address_1 
, so.shiptocity AS City 
, stateconst.name AS State 
, so.shiptozip AS Zip 
, so.billtoname AS Buyer_Name 
, contact.datus AS Buyer_Email 
, qbclass.name AS Class 
, carrier.name AS Carrier 
, CAST(soitem.datescheduledfulfillment as date) AS Fulfillment_Date 
From SO 
JOIN stateconst 
ON so.shiptostateid=stateconst.id 
JOIN qbclass 
ON so.qbclassid=qbclass.id 
JOIN soitem 
ON so.id=soitem.soid 
JOIN carrier 
ON so.carrierid=carrier.id 
JOIN contact 
ON so.customerid=customer.id 
ON customer.accountid=contact.accountid 
WHERE CAST(soitem.datescheduledfulfillment as date) = '5/16/16' 
AND qbclass.name<>'C- Online' AND qbclass.name<>'InterCompany' 
+1

テーブル構造を表示できますか? – Siyual

+0

'CROSS JOIN'を使用する共通の列がない場合、' ON'クローズを使用しない場合しかし、より多くのヘルプが必要な場合は、dbスキーマ、サンプルデータ、および出力を共有してください。 –

+0

テーブルの構造をどのように表示するかはよく分かりませんが、テーブルとそのデータを追跡するためにこれを使用しています:http://fishbowldatadictionary.ilopez.com/ – JonBravo

答えて

1

今のところ、お客様の連絡先をすべて取り戻すようです。私は顧客が会社(例えばAcme Inc.)であり、連絡先がAcme Inc(Bugs Bunny、Daffy Duckなど)の従業員であると仮定しています。あなたが戻ってほしい連絡先を示す連絡先テーブルにフラグのいくつかの並べ替えを持っていない限り、あなたは現在のJOIN連絡先に誰もが引っ張ってくる可能性があり、連絡先ごとに重複した行を作成する可能性があります。

あなたのJOINロジックはかなり近いですが、ステップをスキップしたように見えます。 JOINに連絡する前に、顧客に加入する必要があります。今はJOIN句に投げ込まれているだけです。それを明示的に行います。

Select DISTINCT 
so.num AS Ref 
, so.shiptoname AS Recipient_Full_Name 
, so.shiptoaddress AS Address_1 
, so.shiptocity AS City 
, stateconst.name AS State 
, so.shiptozip AS Zip 
, so.billtoname AS Buyer_Name 
, contact.datus AS Buyer_Email 
, qbclass.name AS Class 
, carrier.name AS Carrier 
, CAST(soitem.datescheduledfulfillment as date) AS Fulfillment_Date 
, contacts.DATUS AS DATUS 
From SO 
JOIN stateconst 
ON so.shiptostateid=stateconst.id 
JOIN qbclass 
ON so.qbclassid=qbclass.id 
JOIN soitem 
ON so.id=soitem.soid 
JOIN carrier 
ON so.carrierid=carrier.id 
--My Change-- 
JOIN customer 
ON so.customerid = customer.id 
JOIN contact 
--Removed this ON so.customerid=customer.id-- 
ON customer.accountid=contact.accountid 
--Done My Change-- 
WHERE CAST(soitem.datescheduledfulfillment as date) = '5/16/16' 
AND qbclass.name<>'C- Online' AND qbclass.name<>'InterCompany' 

あなたのジョインはすべてあなたのスタートテーブルSOに基づいている必要はありません。この場合、SOから開始し、SO.customerid = Customers.IDでCustomersにジョインしてから、Customers.accountid = Contacts.accountidのJOIN Contactsをクリックします。再び、これは現在、あなたの顧客とAccountIDを共有している連絡先を引き取ります。

+0

説明のおかげで、それは私の理解のためにトンを助けました!あなたは、顧客のためのすべての連絡先を引き出すことが正しいです。連絡先テーブルのフラグはCONTACT.TYPEID = '60'なので、最後に別のAND句を追加しました。 – JonBravo

+0

すごく、私は助けることができてうれしい! –

関連する問題