我正在尝试记录过渡表和日期表。
表A:
date
2017-01-01
2017-01-02
2017-01-03
2017-01-04
表B:
state | date_logged | requestno_i
A 2017-01-01 req01
B 2017-01-03 req01
C 2017-01-04 req01
预期结果:
date | state | date_logged | requestno_i
2017-01-01 A 2017-01-01 req01
2017-01-02 A 2017-01-01 req01
2017-01-03 B 2017-01-03 req01
2017-01-04 C 2017-01-04 req01
这是我的尝试:
SELECT
A.date,
B.state,
B.date_logged,
B.requestno_i
FROM TABLE_A A CROSS JOIN TABLE_B B
WHERE requestno_i='req01' and A.date>=B.date_logged
答案 0 :(得分:4)
执行此操作的一种方法是使用CROSS APPLY
而不是CROSS JOIN
。例如:
DECLARE @TableA TABLE ([Date] DATE);
INSERT @TableA ([Date]) VALUES ('2017-01-01'), ('2017-01-02'), ('2017-01-03'), ('2017-01-04');
DECLARE @TableB TABLE ([State] CHAR(1), Date_Logged DATE, RequestNo_i VARCHAR(10));
INSERT @TableB ([State], Date_Logged, RequestNo_i) VALUES ('A', '2017-01-01', 'req01'), ('B', '2017-01-03', 'req01'), ('C', '2017-01-04', 'req01');
SELECT A.[Date], B.[State], B.Date_Logged, B.RequestNo_i
FROM @TableA AS A
CROSS APPLY
(
SELECT TOP 1 *
FROM @TableB
WHERE Date_Logged <= A.[Date]
AND RequestNo_i = 'req01'
ORDER BY Date_Logged DESC
) AS B;