SQL Server: Combine multiple rows into one row

2019-08-25 12:55发布

I've looked at a few other similar questions, but none of them fits the particular situation I find myself in.

I am a relative beginner at SQL.

I am writing a query to create a report. I have read-only access to this DB. I am trying to combine three rows into one row. Any method that only requires read access will work.

That being said, the three rows I have, were obtained by a very long sub-query. Here is the outer shell:

SELECT Availability,
       Start_Date,
       End_Date
FROM (
  -- long subquery goes here (it is several UNION ALLs)
  ...
) AS dual

Here are the rows:

Availability | Start_Date | End_Date
-------------------------------------
99.983       | NULL       | NULL
NULL         | 1/10/2013  | NULL
NULL         | NULL       | 1/28/2013

What I am trying to do is combine the three rows into one row, like so:

Availability | Start_Date | End_Date
-------------------------------------
99.983       | 1/10/2013  | 1/28/2013

I am aware that I could use COALESCE() to put them in one column, but I would prefer to keep the three separate columns.

I can't create or use stored procedures.

Is it possible to do this? Can I have an example for the general case?

1条回答
狗以群分
2楼-- · 2019-08-25 13:49

Have you tried using an aggregate function:

SELECT max(Availability) Availability,
       max(Start_Date) Start_Date,
       max(End_Date) End_Date
FROM (
  -- long subquery goes here (it is several UNION ALLs)
  ...
) AS dual

If you have additional columns, then you would need to add a GROUP BY clause

查看更多
登录 后发表回答