SQL Server:两个表的最大日期

时间:2016-01-19 21:51:09

标签: sql-server-2008

我需要找到客户最后一次为所有客户和所有商品订购商品。我想我会从最后一次客户订购的东西开始。这将涉及两个表oeordhdr_sqloehdrhst_sql都有cus_noord_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

1 个答案:

答案 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