英文:
Rolling up rows and creating a new row per roll up
问题
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.
英文:
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.
答案1
得分: 1
以下提供了您期望的结果吗?
您可以将现有数据与具有>1个DepartmentNames的行合并,然后使用row_number来提供新的序列:
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;
英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论