I have a table called crewWork as follows :
CREATE TABLE crewWork(
FloorNumber int, AptNumber int, WorkType int, simTime int )
After the table was populated, I need to know how many times a change in apt occurred and how many times a change in floor occurred. Usually I expect to find 10 rows on each apt and 40-50 on each floor.
I could just write a scalar function for that, but I was wondering if there’s any way to do that in t-SQL without having to write scalar functions.
Thanks
The data will look like this:
FloorNumber AptNumber WorkType simTime
1 1 12 10
1 1 12 25
1 1 13 35
1 1 13 47
1 2 12 52
1 2 12 59
1 2 13 68
1 1 14 75
1 4 12 79
1 4 12 89
1 4 13 92
1 4 14 105
1 3 12 115
1 3 13 129
1 3 14 138
2 1 12 142
2 1 12 150
2 1 14 168
2 1 14 171
2 3 12 180
2 3 13 190
2 3 13 200
2 3 14 205
3 3 14 216
3 4 12 228
3 4 12 231
3 4 14 249
3 4 13 260
3 1 12 280
3 1 13 295
2 1 14 315
2 2 12 328
2 2 14 346
I need the information for a report, I don’t need to store it anywhere.
If I am not missing anything, you could use the following method to find the number of changes:
determine groups of sequential rows with identical values;
count those groups;
subtract 1.
Apply the method individually for
AptNumberand forFloorNumber.The groups could be determined like in this answer, only there’s isn’t a
Seqcolumn in your case. Instead, anotherROW_NUMBER()expression could be used. Here’s an approximate solution:(I’m assuming here that the
simTimecolumn defines the timeline of changes.)UPDATE
Below is a table that shows how the distinct groups are obtained for
AptNumber.Here
RNis a pseudo-column that stands forROW_NUMBER() OVER (ORDER BY simTime). You can see that this is just a sequence of rankings starting from 1.Another pseudo-column,
RN_Aptcontains values produces by the otherROW_NUMBER, namelyROW_NUMBER() OVER (PARTITION BY AptNumber ORDER BY simTime). It contains rankings within individual groups of identicalAptNumbervalues. You can see that, for a newly encountered value, the sequence starts over, and for a recurring one, it continues where it stopped last time.You can also see from the table that if we subtract
RNfromRN_Apt(could be the other way round, doesn’t matter in this situation), we get the value that uniquely identifies every distinct group of sameAptNumbervalues. You might as well call that value a group ID.So, now that we’ve got these IDs, it only remains for us to count them (count distinct values, of course). That will be the number of groups, and the number of changes is one less (assuming the first group is not counted as a change).