I have the below situation (say tblRecord)
ID RowNum Data
1 1 and seventy nine
1 2 five hundred
1 3 two thousand
I need the output to be
ID Data
1 two thousand five hundred and seventy nine
I have the below query
select ID , Data =
( Select ' ' + cast(Data as varchar(max)) from tblRecord t2
where t2.RowNum= t1.RowNum
and t2.ID =t1.ID
order by t1.RowNum
for xml path(''))
from tblRecord t1
group by t1.ID
But the output is
ID Data
1 five hundred two thousand and seventy nine
Help needed for this.
Thanks
A SELECT query returns results as a rowset. You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.
The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.
We can use FOR XML PATH to prepare a comma-separated string from the existing data. Let's create an Authors table and insert a few records into it. In the data, we can see we have an ID column and the AuthorName column. If we just select the records, it gives the output in the following format.
RAW mode transforms each row in the query result set into an XML element that has the generic identifier <row>, or the optionally provided element name. By default, each column value in the rowset that is not NULL is mapped to an attribute of the <row> element.
Try this:
SELECT DISTINCT
ID, Data = (SELECT ' ' + Data
FROM dbo.tblRecord t2
WHERE t2.ID = t1.ID
ORDER BY t2.RowNum DESC
FOR XML PATH('')
)
FROM dbo.tblRecrd t1
Your first problem was the ORDER BY t1.RowNum
in the inner select - needs to be ORDER BY t2.RowNum
instead. Secondly: this join condition where t2.RowNum= t1.RowNum
is not necessary and causes problems. And thirdly: the GROUP BY
is again neither needed nor helpful - just use the SELECT DISTINCT
to achieve what you're looking for.
Also - not sure why you're casting Data
as VARCHAR(MAX) ???
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With