我有2个表由StudentID和ParkingID加入。我的表B有重复的停车信息。我希望获得StudentID,StudentName,ParkingSpace编号和重复数。这是我的第一篇文章,请原谅我,如果我不遵守所有正确的协议。我很感激帮助。
示例:
Table A:
StudentID StudentName
---- ------
001 Mary
002 Jane
003 Peter
004 Smith
005 Kathy
Table B:
ParkingID ParkingSpace
----- -----
001 25
001 25
002 18
003 74
004 22
005 31
005 31
005 31
005 31
005 31
这是我的目标。
StudentID StudentName ParkingSpace dupCount
---- ------ ------ ------
001 Mary 25 2
005 Kathy 31 5
答案 0 :(得分:2)
测试数据
DECLARE @Table_1 TABLE (StudentID VARCHAR(100),StudentName VARCHAR(100))
INSERT INTO @Table_1 VALUES
('001','Mary'),('002','Jane'),('003','Peter'),
('004','Smith'),('005','Kathy')
DECLARE @Table_2 TABLE
(ParkingID VARCHAR(100),ParkingSpace INT)
INSERT INTO @Table_2 VALUES
('001',25),('001',25),('002',18),('003',74),('004',22),('005',31),
('005',31),('005',31),('005',31),('005',31)
<强>查询强>
SELECT T1.StudentID
,T1.StudentName
,T2.ParkingSpace
,COUNT(T2.ParkingSpace) AS Duplicates
FROM @Table_1 T1 INNER JOIN @Table_2 T2
ON T1.StudentID = T2.ParkingID
GROUP BY T1.StudentID
,T1.StudentName
,T2.ParkingSpace
HAVING COUNT(T2.ParkingSpace) > 1
结果集
╔═══════════╦═════════════╦══════════════╦════════════╗
║ StudentID ║ StudentName ║ ParkingSpace ║ Duplicates ║
╠═══════════╬═════════════╬══════════════╬════════════╣
║ 001 ║ Mary ║ 25 ║ 2 ║
║ 005 ║ Kathy ║ 31 ║ 5 ║
╚═══════════╩═════════════╩══════════════╩════════════╝
答案 1 :(得分:0)
select a.studentId, a.studentName,
b.parkingspace, count(1) as dupcount
from a
join b on a.studentId = b.parkingid
group by a.studentId, a.studentName, b.parkingspace
having dupcount > 1
答案 2 :(得分:0)
SELECT
A.studentID,
A.studentName,
B.parkingSpace,
COUNT(B.parkingSpace)
FROM A
JOIN B ON A.StudentID = B.ParkingID
GROUP BY
A.studentID,
A.studentName,
B.parkingSpace
答案 3 :(得分:0)
这是您的问题的解决方案。
select studentid, studentname, parkingspace , count(*) dupcount
from tablea inner join tableb on tablea.studentid=tableb.parkingid
group by studentid, studentname, parkingspace having count(*)>1
我们计算重复项,并having count(*)>1
仅显示真正的重复项。