Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
286 views
in Technique[技术] by (71.8m points)

sql-server - 最大只能为空值,并将其他SQL Server分组(Max only null value and group the others SQL Server)

I have a table like this:

(我有一张这样的桌子:)

Department  |Jan |Feb |Mar | Apr| 
+-----------+----+----+----+----+
|A          | 1  |NULL|NULL|NULL|    
|A          |NULL|NULL|2   |NULL|    
|A          |NULL|NULL|NULL|7   |    
|B          | 1  |NULL|2   |NULL|    
|B          |NULL|NULL|5   |NULL|    
|B          |NULL|6   |NULL|NULL| 

I want the output will be:

(我希望输出将是:)

+-----------+----+----+----+----+
|Department |Jan |Feb |Mar | Apr| 
+-----------+----+----+----+----+
|A          | 1  |NULL|2   |7   |    
|B          | 1  |6   |2   |NULL|    
|B          |NULL|NULL|5   |NULL|    

Does someone have an idea how to do this?

(有人知道如何执行此操作吗?)

Actually I want to do max only to the null values, and group by to the rest..

(实际上,我只想对空值进行max运算,然后对其余部分进行分组。)

  ask by Tehila translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the order does not really matter (as you say in your comment) then you can do it with ROW_NUMBER() window function:

(如果顺序并不重要(如您在评论中所述),则可以使用ROW_NUMBER()窗口函数进行操作:)

with cte as (
  select *,
    row_number() over (partition by [Department] order by [Jan]) rn1,
    row_number() over (partition by [Department] order by [Feb]) rn2,
    row_number() over (partition by [Department] order by [Mar]) rn3,
    row_number() over (partition by [Department] order by [Apr]) rn4
  from tablename
)
select c1.[Department], c1.[Jan], c2.[Feb], c3.[Mar], c4.[Apr]
from cte c1
inner join cte c2 on c2.[Department] = c1.[Department] and c2.rn2 = c1.rn1
inner join cte c3 on c3.[Department] = c1.[Department] and c3.rn3 = c1.rn1
inner join cte c4 on c4.[Department] = c1.[Department] and c4.rn4 = c1.rn1
where coalesce(c1.[Jan], c2.[Feb], c3.[Mar], c4.[Apr]) is not null
order by c1.[Department], c1.[Jan] desc, c2.[Feb] desc, c3.[Mar] desc, c4.[Apr] desc

See the demo .

(参见演示 。)
Results:

(结果:)

> Department |  Jan |  Feb | Mar |  Apr
> :--------- | ---: | ---: | --: | ---:
> A          |    1 | null |   2 |    7
> B          |    1 |    6 |   5 | null
> B          | null | null |   2 | null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...