TSQL-如何计算实例数

时间:2015-08-07 18:25:09

标签: sql sql-server tsql

我正在使用SQL Server 2014,我需要知道哪一组学生只使用一次操作代码,哪些学生使用的动作代码不止一次。

enter image description here

我正在尝试查看学生是否有5个以上的操作代码之一 例如

SELECT StudentID 
FROM #T 
WHERE ActionCode IN (51201,51206,51207,51208,51209)

我该如何编码呢?

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

SELECT
   StudentID,
   ActionCode,
   ActionCodeCount = Count(*)
FROM
   dbo.StudentActionCodes
WHERE
   ActionCode IN (51201, 51206, 51207, 51208, 51209)
GROUP BY
   StudentID,
   ActionCode
ORDER BY
   StudentID DESC,
   ActionCode
;

See this working in a live demo at SqlFiddle

给定这组值(包括一些不需要的ActionCodes):

StudentID   ActionCode
----------- -----------
987654      51201
987654      51206
987654      51207
987654      51208
987654      51209
987654      51210
987653      51201
987653      51208
987653      51208
987653      51211
987652      51201
987652      51206
987652      51206
987652      51207
987652      51208
987652      51209
987652      51212
987652      51213
987651      51201
987651      51206
987651      51209
987651      51209
987651      51214
987651      51215
987650      51201
987650      51201
987650      51201
987650      51201
987650      51208
987650      51208
987650      51216

结果如下:

StudentID   ActionCode  ActionCodeCount
----------- ----------- ---------------
987654      51201       1
987654      51206       1
987654      51207       1
987654      51208       1
987654      51209       1
987653      51201       1
987653      51208       2
987652      51201       1
987652      51206       2
987652      51207       1
987652      51208       1
987652      51209       1
987651      51201       1
987651      51206       1
987651      51209       2
987650      51201       4
987650      51208       2

您可能也喜欢这个查询:

SELECT
   *
FROM
   dbo.StudentActionCodes S
   PIVOT (
      Count(S.ActionCode) FOR S.ActionCode IN ([51201], [51206], [51207], [51208], [51209])
   ) P
;

这给出了这个结果:

StudentID   51201       51206       51207       51208       51209
----------- ----------- ----------- ----------- ----------- -----------
987650      4           0           0           2           0
987651      1           1           0           0           2
987652      1           2           1           1           1
987653      1           0           0           2           0
987654      1           1           1           1           1

答案 1 :(得分:1)

请尝试以下查询: SQL小提琴链接:http://sqlfiddle.com/#!6/d1dc6/6

它给出了每个学生相同类型的行动总和以及每个学生所有允许行动的总和

SELECT DISTINCT
    StudentID, 
    Actioncode,
    COUNT(1) OVER (PARTITION BY StudentID,Actioncode  ) as [Count_of_this_action_instance],
    COUNT(1) OVER (PARTITION BY StudentID  ) as [Count_of_all_action_instance] FROM StudentActionCodes 
WHERE ActionCode IN (51201,51206,51207,51208,51209)

答案 2 :(得分:0)

计数和分组

SELECT
   StudentID,
   Count(*) as 'count'
FROM
   dbo.StudentActionCodes
GROUP BY
   StudentID;