Reputation: 2961
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?
Upvotes: 0
Views: 5057
Reputation: 183321
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:
SELECT item, dsi, leadtime,
( SELECT COUNT(order_number)
FROM subtable1
WHERE trans_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 730 DAY)
AND DATE_SUB(CURDATE(), INTERVAL 365 DAY)
-- restrict to "current" record from TABLE1:
AND subtable1.item = table1.item
) as OLDORDERS,
( SELECT COUNT(order_number)
FROM subtable1
WHERE trans_date BETWEEN DATE_SUB(CURDATE(), INTERVAL 364 DAY)
AND CURDATE()
-- restrict to "current" record from table1:
AND subtable1.item = table1.item
) as NEWORDERS
FROM table1
;
That's assuming that table1.item
is the primary key, and that subtable1.item
is a foreign-key referring to it. Naturally you'll have to adjust the query if that's not the case.
Upvotes: 4