SQL - combine multiple rows in to a single as a list - sql

How to combine/merge multiple rows into a single rows as a list in SQL.
[original Scenario:]
[Required Scenario:]

SQL Server provides ROW_NUMBER() function to achieve the above
SELECT CASE WHEN ROW_NUMBER() OVER(PARTITION BY [column1] ORDER BY [column1]) > 1
THEN ''
ELSE CAST([column1] AS VARCHAR)
END [column1],
[column2]
FROM <table>;
EDIT : use of STUFF() function
select
[column1],
[column2] = stuff(
(select DISTINCT ' '+[column2] from <table> where [column1] = t.[column1] for xml path('')),
1,1, ''
)
from <table> t group by [column1]
Result :
column1 column2
1 Value 1 Value 2 Value 3
2 Value 4
3 Value 5 Value 6

thanks #Yogesh For your help !!
I have used the below query and it is working fine for me and displays the data as requiredrequired Scenario:
Select distinct ST2.SubjectID,
substring(
(
Select CHAR(10) +ST1.StudentName AS [text()]
From dbo.Students ST1
Where ST1.SubjectID = ST2.SubjectID
ORDER BY ST1.SubjectID
For XML PATH ('')
), 2, 1000) [Students]
From dbo.Students ST2

Related

One column into multiple columns by type, plus concatenating multiples

I have a table like this:
Customer
Number
Type
1
234.567.8910
1
1
234.234.2345
2
2
234.567.5555
1
2
151.513.5464
1
3
845.846.8486
3
I am trying to include this information with information from another table (say... address), but in separate columns by type, and I want to concatenate values that are of the same type so that the return looks like this:
Customer
Cell
Home
Work
1
234.567.8910
234.234.2345
NULL
2
234.567.5555 & 151.513.5464
NULL
NULL
3
NULL
NULL
845.846.8486
When I use the STRING_AGG function, it appends the value for each line of that customer - even if it would be null when the function isn't applied, so the customer 1 has both the cell and home numbers repeated twice.
The only workaround I can find is to select each column in a subquery and join them together. Is that the only option?
Try with FOR XML and PATH.
Query
select [Customer],
stuff((
select distinct ',' + [Number]
from [your_table_name]
where [Customer] = a.[Customer]
and [Type] = 1
for xml path (''))
, 1, 1, '') as [Cell],
stuff((
select distinct ',' + [Number]
from [your_table_name]
where [Customer] = a.[Customer]
and [Type] = 2
for xml path (''))
, 1, 1, '') as [Home],
stuff((
select distinct ',' + [Number]
from [your_table_name]
where [Customer] = a.[Customer]
and [Type] = 3
for xml path (''))
, 1, 1, '') as [Work]
from [your_table_name] as a
group by [Customer];
You need conditional aggregation:
SELECT
Customer,
STRING_AGG(CASE WHEN Type = 1 THEN Number END, ' & ') Cell,
STRING_AGG(CASE WHEN Type = 2 THEN Number END, ' & ') Home,
STRING_AGG(CASE WHEN Type = 3 THEN Number END, ' & ') Work
From table

Uneven pivot without aggregation (filling in the blanks)

I have the following table
Header: user, status, value
row1: u1,A,3
row2: u1,B,5
row3: u1,B,2
row4, u2,A,4
row5: u2,C,8
and I want the output to be a crosstab with NULL if there are not sufficient values from one user to another. In the example the output would be:
Header: status, u1, u2
row1: A,3,4
row2: B, 5, NULL
row3: B, 2, NULL
row4: C, NULL, 8
(I am using SQL Server 2016.)
Not clear if you needed Dynamic (i.e. user columns). Small matter if needed.
Example
Select [Status]
,u1 = max(case when [user]='u1' then Value end)
,u2 = max(case when [user]='u2' then Value end)
From (
Select *
,Grp = Value - Row_Number() over (Partition By [Status] Order by Value)
From YourTable
) A
Group By [Status],[Grp]
Order By 1,2,3
Returns
Status u1 u2
A 3 4
B 2 NULL
B 5 NULL
C NULL 8
EDIT - Dynamic Approach
Declare #SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName([User]) From Yourtable Order by 1 For XML Path('')),1,1,'')
Select #SQL = '
Select [Status],' + #SQL + '
From (
Select *
,Grp = Value - Row_Number() over (Partition By [Status] Order by Value)
From YourTable
) A
Pivot (max([Value]) For [User] in (' + #SQL + ') ) p
Order By 1,2,3
'
Exec(#SQL);

SQL to Make XML Path list Columns

I have the following SQL Server query which cranks out a comma delimited list into one field.
Result looks like this 2003, 9083, 4567, 3214
Question: What would be the best way (SQL syntax) to put this into columns?
Meaning, I need these to show up as 1 column for "2003", 1 column for "9083" 1 column, for "4567" ..etc.
Obviously the number of columns would be dynamic based on the policy ID I give it . Any idea would be most appreciated.
My query is below .
SELECT DISTINCT x.ClassCode + ', '
FROM PremByClass x
WHERE x.PolicyId = 1673885
FOR XML PATH('')
If you take out the XML and the comma you are left with
SELECT DISTINCT x.ClassCode
FROM PremByClass x
WHERE x.PolicyId = 1673885
Which gives you a single column of the values, to turn this into columns you need to PIVOT it. However, you need to specify the names of the columns.
There is some more information in this answer https://stackoverflow.com/a/15931734/350188
You need PIVOT and if number of values could be different - dynamic SQL:
SELECT *
FROM (
SELECT DISTINCT ClassCode,
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) RN
FROM PremByClass
WHERE PolicyId = 1673885
) as t
PIVOT (
MAX(ClassCode) FOR RN IN ([1],[2],[3],[4])
) as pvt
Will give you:
1 2 3 4
-----------------------------
2003 9083 4567 3214
Dynamic SQL will be something like:
DECLARE #sql nvarchar(max),
#columns nvarchar(max)
SELECT #columns = STUFF((
SELECT DISTINCT ','+QUOTENAME(ROW_NUMBER() OVER (ORDER BY (SELECT NULL)))
FROM PremByClass
WHERE PolicyId = 1673885
FOR XML PATH('')
),1,1,'')
SELECT #sql = N'
SELECT *
FROM (
SELECT DISTINCT ClassCode,
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) RN
FROM PremByClass
WHERE PolicyId = 1673885
) as t
PIVOT (
MAX(ClassCode) FOR RN IN ('+#columns+')
) as pvt'
EXEC sp_executesql #sql
Assuming that there's a limit to the amount of numbers in that csv string.
You could cast or convert it to an xml type, and then put the values in as many columns you expect.
In this example it's assumed that there's no more than 6 values in the text:
declare #PolicyId INT = 1673885;
select PolicyId
,x.value('/x[1]','int') as n1
,x.value('/x[2]','int') as n2
,x.value('/x[3]','int') as n3
,x.value('/x[4]','int') as n4
,x.value('/x[5]','int') as n5
,x.value('/x[6]','int') as n6
from (
select
PolicyId,
cast('<x>'+replace(ClassCode,',','</x><x>')+'</x>' as xml) as x
from PremByClass
where PolicyId = #PolicyId
) q;

SQL XML path conversion results error

Actually I m begineer to SQL XML path as so making me professional, Got a scenario...
I have a CTE Function That results as
Data Chars NumberOfOccurance
12 1 1 appears (1 ) times
12 2 2 appears (1 ) times
xx x x appears (2 ) times
and CTE function is :
;with cte as
(
select Data , SUBSTRING(Data,1,1) as Chars,1 as startpos from #t
union all
select Data, SUBSTRING(Data, startpos+1,1) as char,startpos+1 from cte where startpos+1<=LEN(data)
)
select Data,Chars,Cast(Chars as varchar(1)) + ' appears (' + cast(COUNT(*) as varchar(5))+ ' ) times' as 'NumberOfOccurance' from cte
group by data, chars
Actually I just want to make my answer into this :
data Number_of_occurances
12 1 appears (1) times 2 appears (1) times
xx x appears (2) times
I have tries this :
; With Ctea as
(
select Data , SUBSTRING(Data,1,1) as Chars,1 as startpos from #t
union all
select Data, SUBSTRING(Data, startpos+1,1) as char,startpos+1 from ctea where startpos+1<=LEN(data)
)
select Data,Chars,REPLACE((SELECT (Cast(Chars as varchar(1)) + ' appears (' + cast(COUNT(*) as varchar(5))+ ' ) times') AS [data()] FROM Ctea t2 WHERE t2.Data = t1.data FOR XML PATH('')), ' ', ' ;') As Number_of_occurances from ctea as t1
group by t1.data, t1.Chars
It says :
Column 'Ctea.Chars' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
when I use temp table and getting my exact answer , but cant do it CTE
Can anyone make my result ?
The problem has nothing to do with your CTE. It actually lies in the following subquery:
SELECT (Cast(Chars as varchar(1)) +
' appears (' +
cast(COUNT(*) as varchar(5)) +
' ) times') AS [data()]
FROM Ctea t2
WHERE t2.Data = t1.data
FOR XML PATH('')
Note how you are using the aggregate COUNT(*) here as well as the column Chars. You need to group by at least Chars here:
SELECT (Cast(Chars as varchar(1)) +
' appears (' +
cast(COUNT(*) as varchar(5)) +
' ) times') AS [data()]
FROM Ctea t2
WHERE t2.Data = t1.data
GROUP BY t2.Chars
FOR XML PATH('')
Furthermore, you do not want to select or group by t1.Chars in the outer query because it will result in one row per value of Chars:
data chars Number_of_occurances
12 1 1 appears (1) times 2 appears (1) times
12 2 1 appears (1) times 2 appears (1) times
xx x x appears (2) times
Finally you should most likely be using the STUFF function, and not REPLACE, as you are trying to create a space-delimited list ("1 appears (1) times 2 appears (1) times"), not replace all space characters with a space and a semicolon ("1 ;appears ;(1) ;times ;2 ;appears ;(1) ;times").
Therefore your final query should be:
; With Ctea as
(
select Data , SUBSTRING(Data,1,1) as Chars,1 as startpos from #t
union all
select Data, SUBSTRING(Data, startpos+1,1) as char,startpos+1 from ctea
where startpos+1<=LEN(data)
)
select Data,
STUFF((SELECT cast(' ' as varchar(max)) + (Cast(Chars as varchar(1)) + ' appears (' + cast(COUNT(*) as varchar(5))+ ' ) times') AS [data()]
FROM Ctea t2
WHERE t2.Data = t1.data
GROUP BY t2.Chars
FOR XML PATH('')), 1, 1, '') As Number_of_occurances
from ctea as t1
group by t1.data
You can use FOR XML PATH like this for concatenation
;with cte as
(
select Data , SUBSTRING(Data,1,1) as Chars,1 as startpos from #t
union all
select Data, SUBSTRING(Data, startpos+1,1) as char,startpos+1 from cte where startpos+1<=LEN(data)
), CTE2 AS
(
select Data,Chars,Cast(Chars as varchar(1)) + ' appears (' + cast(COUNT(*) as varchar(5))+ ' ) times' as 'NumberOfOccurance' from cte
group by data, chars
)
SELECT Data,(SELECT NumberOfOccurance + ' ' FROM CTE2 c2 WHERE c2.Data = C1.Data FOR XML PATH(''),type).value('.','VARCHAR(MAX)') as Number_of_occurances
FROM CTE2 C1
GROUP BY Data

Duplicates without using While or Cursor in T-SQL

ID Name
1 A
1 B
1 C
2 X
2 Y
3 P
3 Q
3 R
These are the columns in a table. I want to get output like
ID Company
1 A,B,C
2 X, Y
3 P,Q,R
Restriction is that I cannot use WHILE or CURSOR. Please write a query for the same.
This query should do it - uses FOR XML PATH which is new in SQL Server 2005 - hope you are on 2005 or higher, you didn't clearly specify.....
SELECT
ID,
STUFF(CAST((SELECT ','+Name FROM dbo.YourTable t2
WHERE t2.ID = dbo.YourTable.ID
FOR XML PATH(''), TYPE) AS VARCHAR(MAX)), 1, 1, '') AS 'Company'
FROM
dbo.YourTable
GROUP BY
ID
Here's a solution using the CROSS APPLY method:
select id, sub.names
from (
select distinct id from YourTable
) a
cross apply (
select name + ', ' as [text()]
from YourTable b
where b.id = a.id
for xml path('')
) sub(names)
For 2005 version:
CREATE TABLE dbo.TEST([Type] INTEGER, [Name] NVARCHAR(100), [Qty] INTEGER)
GO
INSERT dbo.TEST VALUES(1, N'a', 5)
INSERT dbo.TEST VALUES(1, N'b', 6)
INSERT dbo.TEST VALUES(2, N'c', 44)
INSERT dbo.TEST VALUES(3, N'd', 1)
GO
select [Type],
[Description] = replace((select [Name] + ':' + cast([Qty] as varchar) as 'data()'
from TEST where [Type] = t.[Type] for xml path('')), ' ', ',')
from dbo.TEST t
group by [Type]
go
drop table dbo.TEST
You can group on the ID to get the unique values, then get the comma separated string for each using a for xml query:
select
a.ID,
substring((
select ', ' + Name
from Test1
where Test1.ID = a.ID
for xml path('')
), 3, 1000) as Company
from
TheTable a
group by
a.ID