Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rolling up rows and creating a new row per roll up

I have a table like this:

DepartmentName | SubDivisionName | Importance
Security       | Cyber           | 1
Security       | Airlines        | 2
Security       | Banks           | 3
Health         | Children        | 4
Health         | Elderly         | 5
Housing        | Housing         | 6
Misc           |                 | 7

I want to create a new table ( a temp table ) based off of that to look like this below. Notice that whenever we GROUP BY DepartmentName and number of its GROUP members is bigger than one, it means that DepartmentName has some SubDivisions so we want to insert a new row for **that **and Importance value would get updated accordingly.


DepartmentName | SubDivisionName | Importance
Security       |                 | 1
Security       | Cyber           | 2
Security       | Airlines        | 3
Security       | Banks           | 4
Health         |                 | 5
Health         | Children        | 6
Health         | Elderly         | 7
Housing        | Housing         | 8
Misc           |                 | 9

I tried some GROUP BY to find the ones that have more than one record but still had trouble inserting new rows and correctly updating the importance column.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Does the following provide your expected results?

You can union your existing data with rows that have >1 DepartmentNames and then use row_number to provide the new sequence:

with u as (
    select DepartmentName, SubDivisionName, Importance 
    from t
    union all
    select DepartmentName, null, Min(Importance)
    from t
    group by DepartmentName
    having Count(*) > 1
)
select DepartmentName, SubDivisionName, 
  Row_Number() over(order by Importance, SubDivisionName) as Importance
from u
order by Importance;

Demo Fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading