我需要找到客户最后一次为所有客户和所有商品订购商品。我想我会从最后一次客户订购的东西开始。这将涉及两个表oeordhdr_sql
和oehdrhst_sql
都有cus_no
和ord_dt
。
我在on
select
arcusfil.cus_no, Order_Date.orddt
from
arcusfil_sql arcusfil
join
(SELECT
cus_no, MAX(MaxDate) AS orddt
FROM
(SELECT
cus_no, MAX(ord_dt) AS MaxDate
FROM
oeordhdr_sql
GROUP BY
cus_no
UNION
SELECT
cus_no, MAX(ord_dt) AS MaxDate
FROM
oehdrhst_sql
GROUP BY
cus_no) Order_date ON arcusfil.cus_no = Order_date.cus_no
答案 0 :(得分:0)
您在)
之前错过了结束ON
以关闭您用于JOIN
select
arcusfil.cus_no, Order_Date.orddt
from
arcusfil_sql arcusfil
join
(SELECT
cus_no, MAX(MaxDate) AS orddt
FROM
(SELECT
cus_no, MAX(ord_dt) AS MaxDate
FROM
oeordhdr_sql
GROUP BY
cus_no
UNION
SELECT
cus_no, MAX(ord_dt) AS MaxDate
FROM
oehdrhst_sql
GROUP BY
cus_no) MaxDates
) Order_date ON arcusfil.cus_no = Order_date.cus_no
我喜欢将CTE用于此类查询以保持清洁:
;WITH MaxDates AS (
SELECT cus_no, MAX(ord_dt) AS MaxDate
FROM oeordhdr_sql
GROUP BY cus_no
UNION
SELECT cus_no, MAX(ord_dt) AS MaxDate
FROM oehdrhst_sql
GROUP BY cus_no
),
Order_Date AS (
SELECT cus_no, MAX(MaxDate) AS orddt
FROM MaxDates
GROUP BY cus_no
)
SELECT arcusfil.cus_no, Order_Date.orddt
FROM arcusfil_sql arcusfil
INNER JOIN Order_Date on arcusfil.cus_no = Order_date.cus_no