我正在尝试在所有一个查询中执行所有这些SELECT
语句,因此我将能够进一步对其进行分组。我相信我必须在TABLE1上告诉它JOIN
。我可以告诉你,它应该在名为ITEM
的字段上加入。我已经尝试了几十个JOIN语句,但没有一个可以解决问题,因为我的子查询中有两个WHERE
语句。
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
显示器:
ITEM | DSI | LEADTIME | OLDORDERS | NEWORDERS
PROD-1 0 1 16036 38399
PROD-2 1 0 16036 38399
PROD-3 1 1 16036 38399
再次......我相信我需要JOIN
子查询中的ITEM
字段,但我不知道如何做到这一点,任何想法?
答案 0 :(得分:4)
您实际上并不需要JOIN
,本身;相反,您需要“关联”您的子查询,以便它们引用其包含查询中的数据。
你没有给出确切的表格定义,所以我不能肯定地说,但这是我对你需要的猜测:
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
;
假设table1.item
是主键,而subtable1.item
是引用它的外键。当然,如果情况并非如此,你将不得不调整查询。