计数和分组以获得总计

时间:2014-09-30 16:20:01

标签: sql sql-server tsql

SELECT 
   *, COUNT(examID) AS ExamCount 
FROM 
   ExamSession
GROUP BY
   [examID], [userID], [sessionID]

这给了我一个结果集,但ExamCount有一个' 1'即使考试显示在一行以上,每行...我试图获得examID在结果集中出现的次数。

所以结果集如下所示:

examID | userID | sessionID | ExamCount
---------------------------------------------------------
1111   | xxxxxx | xxxxxx    |   1
1111   | xxxxxx | xxxxxx    |   1
1111   | xxxxxx | xxxxxx    |   1
2222   | xxxxxx | xxxxxx    |   1
2222   | xxxxxx | xxxxxx    |   1
3333   | xxxxxx | xxxxxx    |   1
3333   | xxxxxx | xxxxxx    |   1
3333   | xxxxxx | xxxxxx    |   1
3333   | xxxxxx | xxxxxx    |   1

如何计算examID出现的次数?

谢谢!

4 个答案:

答案 0 :(得分:7)

代码:

COUNT(examID) OVER(PARTITION BY examID) AS ExamCount

答案 1 :(得分:1)

详细说明jbarker回答

if object_id(N'dbo.groupTry',N'U') is not null
    drop table dbo.groupTry
create table dbo.groupTry
(
    examID int,
    userID int,
    sessionID int,
    ExamCount int
)

insert into dbo.groupTry values
(1111, 1234, 4321, 1),
(1111, 9876, 6789, 1),
(1111, 8765, 5678, 1),
(2222, 7654, 4567, 1),
(2222, 6543, 3456, 1),
(3333, 5432, 2345, 1),
(3333, 1987, 1789, 1),
(3333, 1876, 1678, 1),
(3333, 1765, 1567, 1)

select 
    count(g.examID) over(partition by examID) as ExamCount, 
    g.examID,
    g.userID,
    g.sessionID,
    g.ExamCount 
from dbo.groupTry g
group by examID,
    userID,
    sessionID,
    ExamCount

用我自己的简单的话来说,只是意味着:在计算时不要查看所有列,只需查看并计算examID的唯一行(因为我们通过examID进行分区)。

答案 2 :(得分:0)

   SELECT examId, COUNT(examID) AS ExamCount 
   FROM ExamSession
   GROUP BY [examID]

编辑: 如果您需要所有列

select t1.*, t2.ExamCount 
from(
    SELECT *       
    FROM 
       ExamSession 
    GROUP BY
       [examID], [userID], [sessionID]) t1 
inner join (
    SELECT examId, COUNT(examID) AS ExamCount 
       FROM ExamSession
       GROUP BY [examID]) t2
 on t1.examID=t2.examID

答案 3 :(得分:0)

编辑:

select A.examid, B.UserId, b.SessionID, A.ExamCount from 
( SELECT examId, COUNT(examID) AS ExamCount 
   FROM ExamSession
   GROUP BY [examID]) A
JOIN (select [examID] ,[userID]  ,[sessionID] from ExamSession) B
on a.examid = b.examid