Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple SQL rows into one row [duplicate]

Possible Duplicate:
Concatenate many rows into a single text string?

Suppose I have table named tblContractMail. Sample table with data given below:

enter image description here

I need to write a SQL query that produces the following output:

'[email protected];[email protected];[email protected]'

I know two possibilities:

DECLARE @str varchar(4000)
SELECT @str = COALESCE(@str + ';', '') + strContract FROM tblContractMail 
SELECT @str

and:

DECLARE @str varchar(4000)
SET @str = (SELECT strContract + ';' FROM tblContractMail FOR XML PATH(''))
SET @str = SUBSTRING(@str, 1, LEN(@str)-1)
SELECT @str

Is there any way to get this output in a single query (I mean with out declaring any variables)?

like image 529
yeasir007 Avatar asked Jun 03 '12 04:06

yeasir007


People also ask

How do I convert multiple rows to one row in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

How do I combine multiple rows of data into one row?

To merge two or more rows into one, here's what you need to do: Select the range of cells where you want to merge rows. Go to the Ablebits Data tab > Merge group, click the Merge Cells arrow, and then click Merge Rows into One.

How do I duplicate a row in SQL?

To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.

How do you combine repetitive data in SQL?

To combine, use GROUP_CONCAT() function to combine some attributes in two rows into one. As a separator, use hyphens.


1 Answers

The first method relies on the variable, so the answer is no for the first one.

But you can easily use the second approach without a variable, only you need to modify it slightly:

SELECT 
  SUBSTRING(
    (SELECT ';' + strContract FROM tblContractMail FOR XML PATH('')),
    2,
    2147483647
  )

As you can see, the separator goes before the item. As a result, you start cutting the string from the second character, omitting the leading semicolon. The length specifier doesn't have to be precisely the length minus one, you can specify any fairly big number, and the function will return everything from the second character to the end. In this case the maximum int value has been specified.

like image 189
Andriy M Avatar answered Oct 11 '22 16:10

Andriy M