SQL Right Join问题

时间:2017-02-27 08:13:42

标签: sql oracle

我的查询进行了正确的加入,但结果不正确 Null值必须是NAME_2列与A相等的位置,我无法弄清楚出了什么问题。

以下是查询:

http://sqlfiddle.com/#!6/cd45b/1

为未来的读者。表格的定义:

CREATE TABLE S1 (TIME_1 DateTIME, INTERVAL_1 INT, NAME_1 varchar(20),INITIAL_VAL int);
CREATE TABLE S2 (TIME_2 DateTIME, INTERVAL_2 INT, NAME_2 varchar(20), FINAL_VAL int);

与问题相关的数据插页:

INSERT INTO S1 values('10.02.2017 00:00',1, 'B',13);
INSERT INTO S1 values('10.02.2017 01:00',2, 'B',14);
INSERT INTO S1 values('10.02.2017 02:00',3, 'B',10);
INSERT INTO S1 values('10.02.2017 03:00',4, 'B',15);

INSERT INTO S1 values('10.02.2017 00:00',1, 'C',42);
INSERT INTO S1 values('10.02.2017 01:00',2, 'C',10);
INSERT INTO S1 values('10.02.2017 02:00',3, 'C',22);
INSERT INTO S1 values('10.02.2017 03:00',4, 'C',18);


INSERT INTO S2 values('10.02.2017 00:00',1, 'A',12);
INSERT INTO S2 values('10.02.2017 01:00',2, 'A',13);
INSERT INTO S2 values('10.02.2017 02:00',3, 'A',9);
INSERT INTO S2 values('10.02.2017 03:00',4, 'A',16);

INSERT INTO S2 values('10.02.2017 00:00',1, 'B',16);
INSERT INTO S2 values('10.02.2017 01:00',2, 'B',22);
INSERT INTO S2 values('10.02.2017 02:00',3, 'B',20);
INSERT INTO S2 values('10.02.2017 03:00',4, 'B',10);

INSERT INTO S2 values('10.02.2017 00:00',1, 'C',42);
INSERT INTO S2 values('10.02.2017 01:00',2, 'C',15);
INSERT INTO S2 values('10.02.2017 02:00',3, 'C',22);
INSERT INTO S2 values('10.02.2017 03:00',4, 'C',19); 

问题的初步查询:

WITH CTE1
AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY NAME_1) AS V1, * FROM S1
)
,CTE2
AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY NAME_2) AS V2,* FROM S2
)
SELECT
CTE2.NAME_2,
CTE2.TIME_2,
INTERVAL_2,
CTE1.INITIAL_VAL,
CTE2.FINAL_VAL
FROM CTE1
RIGHT JOIN CTE2
ON CTE1.V1=CTE2.V2

2 个答案:

答案 0 :(得分:1)

您的正确加入与生成的ROW_NUMBER匹配。因此,NAME_2值为A A,与NAME_1值不匹配并不重要。

S1中的B与表S2中的ROW_NUMBER匹配,因为它们都得到相同的SELECT ROW_NUMBER() OVER (ORDER BY NAME_1) AS V1, * FROM S1; SELECT ROW_NUMBER() OVER (ORDER BY NAME_2) AS V2,* FROM S2;

请运行此选项以查看正确加入时匹配的内容:

WITH CTE1
AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY NAME_1) AS V1, * FROM S1
)
,CTE2
AS
(
    SELECT ROW_NUMBER() OVER (ORDER BY NAME_2) AS V2,* FROM S2
)
SELECT
CTE2.NAME_2,
CTE2.TIME_2,
INTERVAL_2,
CTE1.INITIAL_VAL,
CTE2.FINAL_VAL
FROM CTE1
RIGHT JOIN CTE2
ON CTE1.NAME_1=CTE2.NAME_2 AND CTE1.INTERVAL_1 = CTE2.INTERVAL_2

编辑: 从评论中回答你的问题。很难知道你究竟需要构建什么,但我认为间隔可能带来一些有趣的结果:

public interface IDbResultSet<T, TCollection>
       where TCollection : ICollection<T>
{
     TCollection Items { get; }
     int TotalRowCount { get; }
}

答案 1 :(得分:0)

Name_1和Name_2的间隔是否始终相同?否则会再次出错。不确定是否只需要在名称列或名称和组合的组合上进行联接。间隔。如果Jakub Szumiato给出的答案已经为您服务,请忽略。我已经采用了一个简单的测试数据,并使用Jakub Szumiato提供的查询执行。这是输出。

enter image description here