我有两张桌子:
客户可以有多个订单
我需要的是每行的previous_order(日期)列
示例:
order_id | order_date | order_client | previous_order
-----------------------------------------------------
1 | 02/02 | 1 | null
2 | 02/03 | 1 | 02/02
3 | 02/10 | 1 | 02/03
4 | 02/10 | 1 | 02/10
我试过这个命令:
从订单
中选择一个。*,b.previous_date加入(从订单a中选择a.order_client,min(a.order_date)作为previous_date
按a.order_client分组)b
on a.order_client = b.order_client
但是使用这个我得到每个客户的第一个订单。
我还看到了lag()和lead()函数。但它们在microsoft sql server 10.50中不可用。
任何人都可以帮我解决这个SQL命令吗?
提前致谢
答案 0 :(得分:0)
也许这就是:
CREATE TABLE #Client (Client_ID INT )
CREATE TABLE #Order (Order_ID INT, Client_ID INT, Order_Date DATE)
INSERT INTO #Client
( Client_ID )
VALUES
( 1 ) -- Client_ID - int
INSERT INTO #Order
( Order_ID, Client_ID, Order_Date )
VALUES
( 1 , 1 , '20150202' ),
( 2 , 1 , '20150203' ),
( 3 , 1 , '20150210' ),
( 4 , 1 , '20150210' )
SELECT
Order_ID AS order_id
, Order_Date AS order_date
, Client_ID AS order_client
, (SELECT MAX(Ord2.Order_Date)
FROM #Order AS Ord2
WHERE
Ord2.Order_Date <= #Order.Order_Date
AND Ord2.Order_ID < #Order.Order_ID
AND Ord2.Client_ID = #Order.Client_ID) AS previous_order
FROM #Order
-- Cleanup
DROP TABLE #Client
DROP TABLE #Order