2014-02-21 57 views
1

我有兩個表由StudentID和ParkingID聯接。我的表B有重複的停車信息。我希望獲得StudentID,StudentName,ParkingSpace數量和重複次數。這是我的第一篇文章,如果我不遵循所有正確的協議,請原諒我。我很感激幫助。連接第二個表具有重複項的表的一個SQL查詢

例子:

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

這兩個表如何鏈接? –

+0

StudentID和ParkingID – user3338724

+1

那麼StudentID和ParkingID代表的是相同的東西?如果是這樣,你可以考慮命名它們相同。 –

回答

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只顯示真正的重複。

http://sqlfiddle.com/#!2/29c2d/2

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 
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 
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 ║ 
╚═══════════╩═════════════╩══════════════╩════════════╝ 
+0

這是不正確的。簡,彼得和史密斯沒有1個副本。他們有1空間和零重複。 – Stainy

相關問題