Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 SQL Query

Author  Topic 

CSK
Constraint Violating Yak Guru

489 Posts

Posted - 2007-10-25 : 09:22:53
Dear Gurus,

i am in the need of assistance again.

scenerio:

id name
1 Lion
1 Rat
1 Mouse
2 Apple
2 Orange

results:
id Name
1 Lion, Rat and Mouse
2 Apple and Orange
---
basically, i need to add a comma if there more that two names with the same id but before the
last name with the same id, i need to add "and" instead of a comma ",". same goes where there's
only two names that share the same id. i need to just put "and".
--
i do not know how to write a script.

can anyone help me to do this ?

Thanks
krishna

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2007-10-25 : 09:40:46
Refer this and modify little bit
http://www.sqljunkies.com/WebLog/amachanic/archive/2004/11/10/5065.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-10-25 : 09:55:18
I have to fiddle around a little, but here it is!
DECLARE	@Sample TABLE (ID INT, Name VARCHAR(9))

INSERT @Sample
SELECT 3, 'Car' UNION ALL
SELECT 1, 'Lion' UNION ALL
SELECT 1, 'Rat' UNION ALL
SELECT 1, 'Mouse' UNION ALL
SELECT 2, 'Apple' UNION ALL
SELECT 2, 'Orange'

-- Show the expected output
SELECT DISTINCT s1.ID,
STUFF(
(
SELECT CASE
WHEN Item = 1 AND Items > 1 THEN ' and '
ELSE ', '
END + s2.Name
FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY s2.ID ORDER BY s2.Name DESC) AS Item,
COUNT(*) OVER (PARTITION BY s2.ID) AS Items,
s2.Name
FROM @Sample AS s2
WHERE s2.ID = s1.ID
) AS s2
ORDER BY Item DESC
FOR XML PATH('')
), 1, 2, '') AS Items
FROM @Sample AS s1
ORDER BY s1.ID



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

CSK
Constraint Violating Yak Guru

489 Posts

Posted - 2007-10-25 : 09:58:29
Peso,

You are really great. This is what I exactly need. thanks peso.

Thanks Thanks

Krishna
Go to Top of Page
   

- Advertisement -