我正在研究SQL,我有两个表
EId Ename
1 john
2 alex
3 piers
4 sara
第二张表是
PID PNAME EID
1 mcndd 1
2 carter 1
3 leare 2
4 jain 2
结果应为
EID count PID
1 2 1
1 2 2
2 2 3
2 2 4
我想要一个查询。我曾尝试过这样的
SELECT t1.EID, COUNT(t1.EID) count,PID
from Employertable t1
INNER JOIN persontable P ON P.EID=t1.EID
Group By t1.EID Having Count(T1.EID) > 1
答案 0 :(得分:1)
您可以使用窗口功能执行此操作。使用这些功能,您可以将聚合数据与非聚合数据相结合:
DECLARE @t1 TABLE ( EID INT )
DECLARE @t2 TABLE ( PID INT, EID INT )
INSERT INTO @t1
VALUES ( 1 ),
( 2 ),
( 3 ),
( 4 )
INSERT INTO @t2
VALUES ( 1, 1 ),
( 2, 1 ),
( 3, 2 ),
( 4, 2 )
SELECT *
FROM ( SELECT t1.EID ,
COUNT(*) OVER ( PARTITION BY t2.EID ) AS C ,
t2.PID
FROM @t1 t1
JOIN @t2 t2 ON t2.EID = t1.EID
) t
WHERE t.C > 1
输出:
EID C PID
1 2 1
1 2 2
2 2 3
2 2 4