合并行并创建一个新行以进行合并。

huangapple go评论63阅读模式
英文:

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;

Demo Fiddle

huangapple
  • 本文由 发表于 2023年2月16日 04:11:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75465004.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定