简体   繁体   中英

SQL QUERY Multiple Tables Newby

I am new to SQL and have the following task I'm trying to complete: I need to create a query that will return a set of results based on a set of dates. Here are my TABLES/columns:

Order Line

order_id,
line_no,
qty_shipped,
total_shipped_qty,
part_id,
part_description,
desired_ship_date,
ship_date,
customer_id

Shipper

packlist,
order_id

Customer

name,
customer_id

Customer Order

PO, 
order_id

I need my output to look like this:

packlist,
order_id,
line_no,
total_shipped_qty,
part_id, 
part_description,
name,
po,
desired_ship_date,
ship_date,

So far I have come up with a query below that gets me all the column data I need from the Order Line Table based on a set of dates. I'm having trouble joining the other tables together to get the rest of the columns I need in my output. Specifically packlist, po, and name from their tables. I need to run this query first:

SELECT ORDER_ID,
       LINE_NO,
       TOTAL_SHIPPED_QTY,
       PART_DESCRIPTION,
       DESIRED_SHIP_DATE,
       SHIP_DATE,
       TOTAL_SHIPPED_QTY
FROM   ORDER_LINE
WHERE  [SHIP_DATE] BETWEEN 'XXXX/XX/XX' AND 'XXXX/XX/XX' 

Based on the results above I need to pull in the rest of the data from the other tables. Any help is greatly appreciated. Thank you

SELECT s.packlist, o.Order_ID, 
o.total_shipped_qty,o.Part_ID, o.Part_Description, co.PO,
c.Name, o.Desired_Ship_Date, o.Ship_Date 
from OrderLine o 
inner join Customers c on c.Customer_ID = o.Customer_ID 
inner join Shipper s on s.Order_ID = o.Order_ID
inner join CustomerOrders co on co.Order_ID = o.Order_ID
WHERE  o.[SHIP_DATE] BETWEEN 'XXXX/XX/XX' AND 'XXXX/XX/XX' 

I don't think you need to join on CustomerOrders at this point.

Just a INNER JOIN between all the tables is what you need

SELECT S.PACKLIST,
       O.ORDER_ID,
       O.TOTAL_SHIPPED_QTY,
       O.PART_ID,
       O.PART_DESCRIPTION,
       C.NAME,
       CO.PO,
       O.DESIRED_SHIP_DATE,
       O.SHIP_DATE
FROM   ORDERLINE O
       JOIN CUSTOMERS C
         ON C.CUSTOMER_ID = O.CUSTOMER_ID
       JOIN SHIPPER S
         ON S.ORDER_ID = O.ORDER_ID
       JOIN CUSTOMERORDER CO
         ON CO.ORDER_ID = O.ORDER_ID
WHERE  O.[SHIP_DATE] BETWEEN 'XXXX/XX/XX' AND 'XXXX/XX/XX' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM