请参阅:http://sqlfiddle.com/#!18/6552d/4
表:
CREATE TABLE Figure(
MonthNumber varchar(10),
Code varchar(10),
Figure int
);
INSERT INTO Figure (MonthNumber, Code, Figure)
VALUES ('5', 'S', '25'),
('5','G', '30'),
('4','K', '30');
CREATE TABLE Person(
Code varchar(10)
);
INSERT INTO Person (Code)
VALUES ('S'),
('G' ),
('K' ),
('D' ),
('J');
查询:
SELECT F.[MonthNumber],
f.[Code],
f.[Figure]
FROM
Figure F
RIGHT JOIN Person P
ON F.[Code] = P.[Code]
WHERE F.[MonthNumber] = '5'
结果:
| MonthNumber | Code | Figure |
|-------------|------|--------|
| 5 | S | 25 |
| 5 | G | 30 |
但我正在寻找这样的结果:
| MonthNumber | Code | Figure |
|-------------|------|--------|
| 5 | S | 25 |
| 5 | G | 30 |
| 5 | K | 30 |
| 5 | D | 0 |
| 5 | J | 0 |
我想将这些数字限制在第5个月,但即使他们没有数字,也会把所有人带回来。我认为使用正确的连接语法对此是正确的,但它没有给我我想要的结果。我无法真正理解我需要的逻辑。任何帮助表示赞赏。感谢
答案 0 :(得分:2)
外部联接似乎正确。为什么使用RIGHT JOIN
代替LEFT JOIN
?后者通常更容易遵循。
SELECT '5' as MonthNumber, p.[Code], COALESCE(f.Figure, 0) as Figure
FROM Person P LEFT JOIN
Figure F
ON F.[Code] = P.[Code] AND F.MonthNumber = '5';
第二个表(在LEFT JOIN
中)的条件需要进入ON
子句。
答案 1 :(得分:0)
我认为这会做它应该做的事情,但不会因为数据而完全提出要求:
SELECT F.[MonthNumber], -- this wont select 5 for all rows, but you can hard code this to the 5
P.[Code],
ISNULL(f.[Figure], 0) AS Figure
FROM
Person P
LEFT OUTER JOIN Figure F ON P.[Code] = F.[Code]
AND F.[MonthNumber] = '5'
答案 2 :(得分:0)
您可以使用下面的查询。
更新小提琴 - http://sqlfiddle.com/#!18/6552d/24
SELECT
MonthNumber= ISNULL(MonthNumber,'5'),
P.Code,
Figure= ISNULL(Figure,0)
FROM
Figure F
RIGHT JOIN Person P
ON F.[Code] = P.[Code]
AND F.[MonthNumber] ='5'
答案 3 :(得分:0)
Try this I hope it helps
CREATE TABLE #Figure(
MonthNumber varchar(10),
Code varchar(10),
Figure int
);
INSERT INTO #Figure (MonthNumber, Code, Figure)
VALUES ('5', 'S', '25'),
('5','G', '30'),
('4','K', '30');
CREATE TABLE #Person(
Code varchar(10)
);
INSERT INTO #Person (Code)
VALUES ('S'),
('G' ),
('K' ),
('D' ),
('J');
SELECT F.[MonthNumber],
P.[Code],
f.[Figure]
FROM #Person p
LEFT JOIN #Figure F
ON P.[Code] = F.[Code]
WHERE F.[MonthNumber] = '5'
or F.[MonthNumber] is null