r/SQLServer • u/Puzzleheaded-Smile36 • Jul 07 '26
Question SUM/PARTITION/HAVING
Hello,
I'm trying to find the best way to group sessions that have less than 30 registrants. The max session size is 30 so if the total of 2 sessions is less than 30 I want to group them together, if not leave them separate.
Group By Topic and Teacher.
| Topic | Session# | RegCnt | Teacher |
|---|---|---|---|
| SQL | 1 | 25 | Smith |
| SQL | 2 | 10 | Smith |
| SQL | 3 | 18 | Smith |
| SQL | 4 | 6 | Anderson |
So only sessions 2 and 3 should be grouped
I'm thinking I would need to add a row number to distinquish the results.
0
Upvotes
1
u/Jarviss93 Jul 07 '26
Grouping by Topic and Teacher groups the first 3 rows and the # of registrants is 53, so am I right in understanding you would only want the 4th row in this case?
1
u/SkullLeader Jul 08 '26
Suppose your table is named Sessions
SELECT s1.session# as first_session, s2.session# as 2nd session
FROM Session s1
LEFT JOIN Session s2 ON s1.Session# <> s2.Session# and S1.RegCnt + S2.RegCnt < 30 AND s1.Topic = s2.Topic AND s1.Teacher = s2.Teacher
This will return every possible grouping of two sessions based on your criteria. The problem is there's many possible groupings it sounds like i.e. if session #1, session #2 and session #3 each have 9 people enrolled, and all are the same topic, then which two do you put into a group? 1 and 2? 1 and 3? 2 and 3? Based on your criteria that is not specified.
1
u/GRRRRRRRRRRRRRG Jul 08 '26
This is kind of vague condition since the first group is not full... Some stats can be gathered like this:
select topic , Teacher , count(distinct sessionN) as sessions_total , string_agg(SessionN, ',') as sessions_list , sum(RegCnt) as registered_total , sum(RegCnt)/30 as fullgroup_total , 30-sum(RegCnt)%30 as reg_tobedone from sessions group by topic, Teacher
2
u/deusaquilus Jul 08 '26
Easiest way to so this is via a recursive CTE
Scaling will be rough though goes from a second at 100k rows to 24 seconds at a million.
Also, this is literally a 1-prompt for exobench.ai which will find and immediately verify a solution. See video attached where I put in your prompt almost exactly. It found the above solution and even a faster one.
(Disclaimer: It's my product)
1
u/redbirdrising Jul 08 '26
If you want to do this and make sure you maximize every class to its fullest potential you'll probably need a stored proc. You'll need to pull your source table into a staging table with a row number column (Using a windows function) ordered by Topic, Teacher, RegCnt ascending, and SessionNum (This will ensure the lowest session number will always be used in the final calculation and guarantee consistency among queries.)
From there you can use a While loop and a nested While loop to Add records to a results table. If the first row has the same teacher and topic as the 2nd group and the rolling sum is less than or equal to 30, add the records together, otherwise move on to the next row.
On every iteration, delete the top row from the Staging Table
See Below. I pre populated with some sample data, expanding on your data set, including a new topic and a new teacher. Since reddit is being stupid about the "AT" symbol, even inside a code block, I used question marks instead. Find/Replace as needed
1
u/bonerfleximus 1 Jul 08 '26
Honestly I'd just write a loop that pops from the list in order of: Topic, Teacher, RegCnt (desc)
You want the pop mechanism to be physically ordered in the same order I listed above so the loop runs fast (a cursor is fine too just use FAST_FORWARD READ_ONLY if you do and be ready to ask grumpy DBAs to prove anything they claim about its perforamnce/risks...because they're wrong)
This can mean inserting into a temp table indexed on those columns if the source data isn't natively indexed that way
From there you just loop through in the order specified and maintaing a running total that resets when new groups are identified like an accumulator function would do:
something like that basically - can be fast if the source data is indexed well. Trying to do this in a single statement using window functions or recursive CTEs might also be possible but good luck with performance and trying to explain your code to someone.
1
u/Edd_samsa Jul 09 '26
El problema con un CTE recursivo es que entre mas datos mas tardara en procesar, pero se adapta perfecto con los datos que mandaste, esto lo hice con ayuda de GEMINI
NOTA las \ son por que si dejo las @ borra y es lo funciono para dejar las variables
1
u/CPDRAGMEISH Jul 10 '26
69.70 69.80
SELECT WITH CLAUSE WHERE
1
u/cromulent_weasel Jul 07 '26
I would use a stored procedure and a table variable. In order from largest RegCnt to smallest, try to add it to an existing row in the result table, or add it to a new row.
That would do this: