Click here to Skip to main content
15,919,028 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear Friends,

I have table My_Table and columns - Date, Message
The Message can be any no. of Message in a Day.
Eg: Date Message
01-08-2012 MSG1
01-08-2012 MSG2
31-07-2012 MSG3
30-07-2012 MSG4
Now I was to display as for the Day : 01-08-2012 - MSG1, MSG2

I have tried like this
SQL
SELECT MSG=COALESCE(MAX(CASE WHEN GENT = 1 THEN Message END), '') + 
COALESCE(MAX(CASE WHEN GENT = 2 THEN Message END), '')  + 
COALESCE(MAX(CASE WHEN GENT = 3 THEN Message END), '') ,SDATE FROM (
SELECT TOP 10 GENT=RANK() OVER(PARTITION BY DATE ORDER BY DATE DESC),* FROM
My_Table WITH (NOLOCK) ORDER BY DATE DESC)O GROUP BY DATE ORDER BY DATE DESC

But this static and I ve mentioned as 3.
I want to make it as dynamic. Kindly guide me on this.
Posted

Why cant you try this

SQL
Select distinct Date,
(
SELECT SUBSTRING(
(
SELECT '+' + T2.Message
FROM EMptest T2
where T2.Date=T1.Date
FOR XML PATH('')),2,200000) AS Message
) as Message
from EMptest as T1
 
Share this answer
 
Comments
Arunprasath Natarajan 1-Aug-12 7:16am    
Tan Q, Santhosh. Its works fine. If you dont mind can you explain how you have used this.
Santhosh Kumar Jayaraman 1-Aug-12 7:28am    
The inner sub-query, concatenates a + in front of each additional result for the message obtained when the Date of the sub-query matches the distinct Date of the parent query. This gives us a string with +.

You can replace this + with Comma.

Then we are substring it from second character , so that we can exclude the leading + symbol.
Arunprasath Natarajan 1-Aug-12 8:10am    
Yeah I understand that, but FOR XML PATH('') wat is the use of it.
Santhosh Kumar Jayaraman 1-Aug-12 8:22am    
Its similar to COALESCE. XMLpath is a new builtin function came with SQL server 2005, It will concatenate values with comma separated or any symbols
Arunprasath Natarajan 1-Aug-12 9:46am    
Tan q so much Santhosh...
I don't think this can work. I think you'll find it easier to get the data, ordered by date, and then step through it to build the result set you want, in code. I am sure it can be done in SQL, but I suspect a code solution will be easier.

How does MAX work on a string ?
 
Share this answer
 
Comments
Arunprasath Natarajan 1-Aug-12 6:18am    
It works fine. But i dont know how to merge it according to rows present in the table (Dynamic).
Christian Graus 1-Aug-12 6:30am    
Really ? I don't see how Max is doing anything good in here. The only way I can see to do what you want, is to build a SQL string an execute it, I don't see any other way to get it to look up values you don't know at the time the proc is written. Of course, you can just write it up to a huge number and hope you never get that high ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900