从 2 个不同的表中查找计数
Finding the count from 2 different tables
我有 3 个表 - 2 个输入表和 1 个查找表
Tab1
Id
4
4
5
6
8
2
Tab2
ID
4
4
1
1
2
6
tab3
ID Name
1 One
2 two
3 three
4 four
5 five
6 six
7 seven
8 eight
我需要一个查询来帮助我获得
Count Name
1 One
1 two
0 three
1 four
1 five
1 six
0 seven
1 eigh
我已经尝试了 In
等,但我无法得到结果。此外,完全连接对 ID 计数两次而不是一次。
SELECT
COUNT(DISTINCT a.id) + COUNT(DISTINCT b.id) AS Total,
c.id
FROM c
INNER JOIN a ON a.id= b.id
LEFT OUTER JOIN b ON c.id = b.id
GROUP BY c.id
我试过了,但没有得到想要的结果。
如果我正确理解了这个问题,一个可能的解决方案是使用 UNION
(从输入 tables 中排除重复项)和适当的 JOIN
使用查找 table:
表格:
SELECT Id INTO Tbl1
FROM (VALUES (4), (4), (5), (6), (8), (2)) v (Id)
SELECT Id INTO Tbl2
FROM (VALUES (4), (4), (1), (1), (2), (6)) v (Id)
SELECT Id, Name
INTO tbl3
FROM (VALUES
(1, 'One'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five'), (6, 'six'), (7, 'seven'), (8, 'eight')
) v (Id, Name)
声明:
SELECT t.Name, Count = COUNT(j.Id)
FROM tbl3 t
FULL JOIN (
SELECT Id FROM tbl1
UNION
SELECT Id FROM tbl2
) j ON t.Id = j.Id
GROUP BY t.Name
我有 3 个表 - 2 个输入表和 1 个查找表
Tab1
Id
4
4
5
6
8
2
Tab2
ID
4
4
1
1
2
6
tab3
ID Name
1 One
2 two
3 three
4 four
5 five
6 six
7 seven
8 eight
我需要一个查询来帮助我获得
Count Name
1 One
1 two
0 three
1 four
1 five
1 six
0 seven
1 eigh
我已经尝试了 In
等,但我无法得到结果。此外,完全连接对 ID 计数两次而不是一次。
SELECT
COUNT(DISTINCT a.id) + COUNT(DISTINCT b.id) AS Total,
c.id
FROM c
INNER JOIN a ON a.id= b.id
LEFT OUTER JOIN b ON c.id = b.id
GROUP BY c.id
我试过了,但没有得到想要的结果。
如果我正确理解了这个问题,一个可能的解决方案是使用 UNION
(从输入 tables 中排除重复项)和适当的 JOIN
使用查找 table:
表格:
SELECT Id INTO Tbl1
FROM (VALUES (4), (4), (5), (6), (8), (2)) v (Id)
SELECT Id INTO Tbl2
FROM (VALUES (4), (4), (1), (1), (2), (6)) v (Id)
SELECT Id, Name
INTO tbl3
FROM (VALUES
(1, 'One'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five'), (6, 'six'), (7, 'seven'), (8, 'eight')
) v (Id, Name)
声明:
SELECT t.Name, Count = COUNT(j.Id)
FROM tbl3 t
FULL JOIN (
SELECT Id FROM tbl1
UNION
SELECT Id FROM tbl2
) j ON t.Id = j.Id
GROUP BY t.Name