对于这个例子,我们将有2个表。表A和表B.表A包含我的所有数据,表B包含数字代码列表。如何选择计数。到目前为止我已经
了select ID, count(Table A Codes that are in TableB) as SharedCodes
into #TableC
from #TableA
group by ID
正确的方法是什么?
示例数据: 表A:
ID | Code
----------------
1 A1
1 A2
1 A3
2 B1
2 B2
2 B3
3 C1
3 C2
3 C3
表B:
Code
-----
A2
A3
B1
C1
C2
C3
所以,上面的查询应该返回
ID | SharedCodes
-----------------------
1 2
2 1
3 3
答案 0 :(得分:0)
测试数据
DECLARE @TABLEA TABLE (ID INT,Code VARCHAR(5))
INSERT INTO @TABLEA VALUES
(1,'A1'),(1,'A2'),(1,'A3'),(2,'B1'),(2,'B2'),
(2,'B3'),(3,'C1'),(3,'C2'),(3,'C3')
DECLARE @TABLEB TABLE (Code VARCHAR(5))
INSERT INTO @TABLEB VALUES
('A2'),('A3'),('B1'),('C1'),
('C2'),('C3')
<强>查询强>
SELECT A.ID
,COUNT(B.Code) AS SharedCodes
INTO #TempTable
FROM @TABLEA A INNER JOIN @TABLEB B
ON A.Code = B.Code
GROUP BY A.ID
SELECT * FROM #TempTable
结果集
╔════╦═════════════╗
║ ID ║ SharedCodes ║
╠════╬═════════════╣
║ 1 ║ 2 ║
║ 2 ║ 1 ║
║ 3 ║ 3 ║
╚════╩═════════════╝