SQL Server: Combine multiple rows into one row

寵の児 提交于 2019-12-13 06:59:09

问题


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:


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



来源:https://stackoverflow.com/questions/14572395/sql-server-combine-multiple-rows-into-one-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!