Author |
Topic |
snow12
Yak Posting Veteran
74 Posts |
Posted - 2012-06-26 : 15:55:26
|
Hello I have a query to CONCATENATE the column:select coalesce(cast(IDName as varchar)+ ',', '')fromfrom the studentI have the results:IDName11111,11111,11111,22222,22222,22222However, I only want distinct IDName such as 11111 and 22222select coalesce(cast(distinct IDName as varchar)+ ',', '')fromfrom the studentI got syntax error. How to I achieve this?Your help is always appreciated. |
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2012-06-26 : 16:05:23
|
[code]-- setupDECLARE @t TABLE(IDName VARCHAR(10))INSERT @t SELECT11111 UNION ALL SELECT 11111 UNION ALL SELECT 11111 UNION ALL SELECT 22222 UNION ALL SELECT 22222 UNION ALL SELECT 22222-- end setup-- querySELECT STUFF((SELECT DISTINCT ','+idnameFROM @t FOR XML PATH('')),1,1,'')[/code]Just change the reference to @t to match your table name. |
|
|
snow12
Yak Posting Veteran
74 Posts |
Posted - 2012-06-26 : 16:32:52
|
Thank you very much for the quick response. I have date condition.SELECT STUFF((SELECT DISTINCT ','+idnameFROM @t FOR XML PATH('')),1,1,'')where date >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0) AND date < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 1)It gave me the error: Msg 207, Level 16, State 1, Line 3Invalid column name 'date'.Msg 207, Level 16, State 1, Line 4Invalid column name 'date'. but my @t did has column dateWhere I missed? |
|
|
robvolk
Most Valuable Yak
15732 Posts |
Posted - 2012-06-26 : 16:56:05
|
SELECT STUFF((SELECT DISTINCT ','+idnameFROM @t WHERE DATE >= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)AND DATE < DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 1)FOR XML PATH('')),1,1,'') |
|
|
snow12
Yak Posting Veteran
74 Posts |
Posted - 2012-06-26 : 17:21:07
|
Thank you very much! You are super! |
|
|
|
|
|