I am trying to do all of these SELECT statements in all one query so I will be able to further it and group it. I believe I have to tell it to JOIN on TABLE1. I can tell you that it should be JOINing on the field called ITEM. I have tried dozens of JOIN statements none of which does the trick because I have two WHERE statements in my subqueries.
SELECT ITEM, DSI, LEADTIME,
(SELECT COUNT(ORDER_NUMBER) FROM SUBTABLE1 TR1 WHERE TRANS_DATE BETWEEN DATE_SUB(curdate(), INTERVAL 730 DAY) AND DATE_SUB(curdate(), INTERVAL 365 DAY))
as OLDORDERS,
(SELECT COUNT(ORDER_NUMBER) FROM SUBTABLE2 TR2 WHERE TRANS_DATE BETWEEN DATE_SUB(curdate(), INTERVAL 364 DAY) AND curdate())
as NEWORDERS
FROM TABLE1
Displays:
ITEM | DSI | LEADTIME | OLDORDERS | NEWORDERS
PROD-1 0 1 16036 38399
PROD-2 1 0 16036 38399
PROD-3 1 1 16036 38399
Again…I believe I need it to JOIN the field ITEM on the subqueries, but I do not know how to do this, any ideas?
You don’t actually need a
JOIN, per se; rather, you need to “correlate” your subqueries, so that they refer to data in their containing query.You haven’t given your exact table definitions, so I can’t say for sure, but here’s my guess at what you need:
That’s assuming that
table1.itemis the primary key, and thatsubtable1.itemis a foreign-key referring to it. Naturally you’ll have to adjust the query if that’s not the case.