1

I have many rows for the same data but each row has a different columns populated. I want to join all these rows into a single row. I have tried group by, but the dataset has 1000 columns. Any suggestions?

SELECT TOP 100 * 
FROM [Hilltopsamplerfix].[dbo].[tempHilltopWaterQualityExtractPivot]
WHERE [SiteName] = 'site' AND [RunDate] = 'xxx'

Example of the data

I can't paste an image because my reputation is under 10

+------------------------------+
| Site column1 column2 column3 |
+------------------------------+
| SITE1 NULL   NULL    76      |
| SITE1 NULL   23      NULL    |
| SITE1 NULL   NULL    NULL    |
+------------------------------+

Desired output:

+------------------------------+
| Site column1 column2 column3 |
+------------------------------+
| SITE1 NULL   23      76      |
+------------------------------+
1
  • 1
    You need to at least show us your input and desired output. Commented Aug 19, 2015 at 2:38

2 Answers 2

2

You need to use group by:

select site, max(column1) as column1, max(column2) as column2, . . .
from [Hilltopsamplerfix].[dbo].[tempHilltopWaterQualityExtractPivot]
group by site;

You can get the columns in the table from information_schema.columns and construct the logic in the SQL or Excel. For example

select '    max(' + column_name + ') as ' + column_name + ', '
from information_schema.columns
where table_name = 'tempHilltopWaterQualityExtractPivot' and
      column_name <> 'site';

Then copy the results into the query window.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Gordon, your help is appreciated. I tried the second script you provided. but the output is "(No column name)" I tried a few ways to make it work but was unable to.
@PythonGeo . . . Can you edit your question and put in an example of the query you get?
Hi Gordon, I was trying in python, so might not be appropriate to the SQL question.
1

Try this below SQL, Based on Gordon

Declare @Cols Varchar(Max)
select @Cols= coalesce(@Cols+',', '')+ ' max(' + column_name + ') as ' + column_name
from information_schema.columns
where table_name = 'tempHilltopWaterQualityExtractPivot' and Column_Name <> 'site'

Declare @Query Varchar(max)
SET @Query='Select Site, '+ @Cols+' From tempHilltopWaterQualityExtractPivot Group by Site'
EXEC(@Query)

2 Comments

Thanks Selva. But I only get "Command(s) completed successfully." in return. A table is not produced.
Hi Geo, Hope you are executed entire script at one shot without excluding EXEC statement especially. In my environment it is working fine and return maximum results from an table. If you removed the EXEC statement kindly include and test once again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.