0

我正在尝试SELECT在所有一个查询中执行所有这些语句,因此我将能够对其进行进一步处理并将其分组。我相信我必须JOIN在 TABLE1 上告诉它。我可以告诉你,它应该在名为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,但我不知道该怎么做,有什么想法吗?

4

1 回答 1

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是引用它的外键。当然,如果不是这种情况,您将不得不调整查询。

于 2012-10-09T19:22:43.753 回答