返回在连接SQL Server中不匹配的结果

时间:2018-05-04 08:32:34

标签: sql sql-server join

请参阅此http://sqlfiddle.com/#!18/8fe2a/13

我有桌子

CREATE TABLE Figure(
MonthNumber varchar(10),
Code varchar(10),
Figure int
);

INSERT INTO Figure (MonthNumber, Code, Figure)
VALUES ('5', 'S', '25'),
('5','G', '30');

CREATE TABLE Other(
MonthNumber varchar(10),
Code varchar(10),
Figure int
);

INSERT INTO Other (MonthNumber, Code, Figure)
VALUES ('5', 'S', '25'),
('5','G', '30'),
('4','K', '40'),
('3','D', '20'),
('2','J', '25');

查询:

SELECT * FROM
Figure f1
RIGHT JOIN 
Other O
ON F1.[Code] = O.[Code]
OR 
o.[MonthNumber] = MONTH(GETDATE())-1
WHERE f1.[MonthNumber] = MONTH(GETDATE())

结果:

| MonthNumber | Code | Figure | MonthNumber | Code | Figure |
|-------------|------|--------|-------------|------|--------|
|           5 |    S |     25 |           5 |    S |     25 |
|           5 |    S |     25 |           4 |    K |     40 |
|           5 |    G |     30 |           5 |    G |     30 |
|           5 |    G |     30 |           4 |    K |     40 |

然而,我正在寻找这个月的结果,但也包括那些可能已经有过前几个月的数字而不是本月数字的人。

期望的结果:

| MonthNumber | Code | Figure |
|-------------|------|--------|
|           5 |    S |     25 |
|           5 |    G |     25 |
|           5 |    K |      0 |
|           5 |    D |      0 |
|           5 |    J |      0 |

我无法确定我在加入时需要什么。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

你似乎想要这样的逻辑:

SELECT MONTH(GETDATE()) as MonthNumber, 
       MONTH(GETDATE()) as Code,
       f.Figure
FROM (SELECT DISTINCT code FROM Other) c LEFT JOIN
     Other o 
     ON c.Code = o.Code LEFT JOIN
     Figure f
     ON f.[Code] = c.[Code] AND
        f.[MonthNumber] = MONTH(GETDATE())
ORDER BY figure desc;

Here是SQL小提琴。我没有费心为COALESCE()加入FigureNULL似乎是合适的返回值。

答案 1 :(得分:0)

试试这个

SELECT 
    O.* 
FROM
    Figure f1
RIGHT JOIN 
    Other O
ON 
    F1.[Code] = O.[Code]
AND 
    (
        f1.[MonthNumber] = MONTH(GETDATE())
    OR 
        (
            o.[MonthNumber] = MONTH(GETDATE())-1
        AND 
            f1.[MonthNumber] != MONTH(GETDATE())
        )
    )

<强>演示

  

http://sqlfiddle.com/#!18/8fe2a/44