sql - TSQL- How to count number of instances -
i'm using sql server 2014 , need know set of students have action code used once, , students have action code used more once.
i'm trying see if student has more 1 of 5 action codes.
e.g.
select studentid #t actioncode in (51201,51206,51207,51208,51209)
how code please?
thank help.
select studentid, actioncode, actioncodecount = count(*) dbo.studentactioncodes actioncode in (51201, 51206, 51207, 51208, 51209) group studentid, actioncode order studentid desc, actioncode ;
see working in live demo @ sqlfiddle
given set of values (including unwanted 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
here results:
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
you might enjoy query:
select * dbo.studentactioncodes s pivot ( count(s.actioncode) s.actioncode in ([51201], [51206], [51207], [51208], [51209]) ) p ;
which gives result:
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
Comments
Post a Comment