2017-09-27 65 views
1

我有两个表的内容:SQL返回同时匹配与来自其他表

表时间表(具有固定的内容)

Value | 
------- 
1 
2 
3 
4 
5 
6 
7 

表PROD_ENTRY(从时间到时间条目)

entry_1    | entry_2 | entry_3 | 
--------------------------------------------------- 
2017/09/25 01:25:00  1    aaa 
2017/09/25 01:26:00  1    bbb 
2017/09/25 03:32:00  2    ccc 
2017/09/25 04:15:00  3    ddd 
2017/09/25 05:05:00  5    eee 
2017/09/26 13:25:00  7    fff 

我想表总是返回格式,而表B项匹配到返回

new_value | entry_time   | entry_2 | entry_3 | 
---------------------------------------------------------- 
    1  2017/09/25 01:26:00  1  bbb 
    2  2017/09/25 03:32:00  2  ccc 
    3  2017/09/25 04:15:00  3  ddd 
    4  null      null  null 
    5  2017/09/25 05:05:00  5  eee 
    6  null      null  null 
    7  null      null  null 

以下是我的代码:

SELECT 
coalesce(T1.entry_2, T2.Value) as timecode , 
T1.* 
FROM 
(SELECT tt.*           ---- 
FROM prod_entry tt          | 
INNER JOIN            | 
(SELECT entry_2, MAX(entry_time) AS MaxDateTime   |- to remove duplicated entry_2 
FROM prod_entry           | 
GROUP BY entry_2) newtt         | 
ON tt.entry_2 = groupedtt.entry_2       | 
AND tt.entry_time = newtt.MaxDateTime) T1    ---- 
FULL OUTER JOIN TimeLine T2 
on T1.entry_3 = T2.Value 
WHERE (T1.entry_3 is null or T2.Value is null) 
OR 
T1.entry_time > '2017-09-25 00:00:00' AND T1.entry_time < '2017-09-25  23:59:00' AND T1.entry_1 = '1' 
order by timecode 

但是我得到以下,以NEW_VALUE“7”缺少

new_value | entry_1    | entry_2 | entry_3 | 
---------------------------------------------------------- 
    1  2017/09/25 01:26:00  1  bbb 
    2  2017/09/25 03:32:00  2  ccc 
    3  2017/09/25 04:15:00  3  ddd 
    4  null      null  null 
    5  2017/09/25 05:05:00  5  eee 
    6  null      null  null 

我可以知道我在删除重复做哪部分出错误?

+0

您正在使用哪个版本的SQL? –

+0

您好Tim,我正在SSRS 2008上运行此查询 – jctan

+0

Left justified SQL ...很难阅读... – jarlh

回答

1

由于您使用的是SQL Server,我认为最简单的方法就是使用ROW_NUMBER,并在两个表之间使用基本左连接。然后,子查询并仅保留timelime表中每个值的最新行。

SELECT 
    new_value, entry_time, entry_2, entry_3 
FROM 
(
    SELECT 
     t1.Value AS new_value, 
     t2.entry_1 AS entry_time, 
     t2.entry_2, 
     t2.entry_3, 
     ROW_NUMBER() OVER (PARTITION BY t1.Value ORDER BY t2.entry_1 DESC) rn 
    FROM TIMELINE t1 
    LEFT JOIN PROD_ENTRY t2 
     ON t1.Value = t2.entry_2 
) t 
WHERE t.rn = 1; 

输出:

enter image description here

演示在这里:

Rextester

0

我会用LEFT JOINGROUP BY

SELECT tt.value AS new_value, 
     tt.entry_1 AS entry_time, 
     tt.entry_2, 
     pe.entry_3 
FROM 
(
    SELECT t.value, MAX(p.entry_1) AS entry_1, p.entry_2 
    FROM TIMELINE t 
    LEFT JOIN PROD_ENTRY p ON p.entry_2 = t.value 
    GROUP BY t.value, p.entry_2 
) tt 
LEFT JOIN PROD_ENTRY pe ON pe.entry_2 = tt.value and pe.entry_1 = tt.entry_1 
相关问题