I have a column that uses an alias in my SQL query. The results of the aliased column are comma-separated lists of languages spoken by the teacher.
SELECT
Teacher.LastName,
STUFF((SELECT DISTINCT ', ' + COALESCE((TeacherLanguage.LanguageName), '')
FROM TeacherLanguage
INNER JOIN TeacherLanguageRel ON Teacher.TeacherId = TeacherLanguage.TeacherId
AND TeacherLanguage.LanguageId = TeacherLanguageRel.LanguageId
FOR XML PATH('')), 1, 1, '') AS 'Languages'
FROM
Teacher
Is there a way to filter the results using the values in the Languages column? Attaching a WHERE operator to the end of the query doesn't appear to work.
For example
WHERE Languages LIKE '%spanish%'
results in an error:
Invalid column name 'Languages'.
You can't do as you intend with your existing query as the where clause is evaluated before the Languages alias is defined.
You could do what you intend by turning your existing query into a derived table by wrapping in an outer select,
select * from (
<your existing query>
)t
where Languages like '%spanish%'
However that will mean you are reading rows you don't want, which you could just filter out in your current query. I believe the following should work - untested of course.
select t.LastName, Stuff((
select distinct ', ' + Coalesce((TeacherLanguage.LanguageName), '')
from TeacherLanguage tl
join TeacherLanguageRel tlr on tlr.LanguageId=tl.LanguageId
where tl.TeacherId=t.TeacherId
and tl.language like '%spanish%'
for xml path('')
), 1, 1, '') as Languages
from Teacher t
Note I've used column aliases in your query, and quotes should be reserved for string literals, not column aliases - Languages is not a reserved word so is fine as-is. This also of course assumes SQL Server.
Additionally since SQL Server 2017, for XML path is obsolete and can be replaced with string_agg.
Can anyone help me make this query work for SQL Server 2014?
This is working on Postgresql and probably on SQL Server 2017. On Oracle it is listagg instead of string_agg.
Here is the SQL:
select
string_agg(t.id,',') AS id
from
Table t
I checked on the site some xml option should be used but I could not understand it.
In SQL Server pre-2017, you can do:
select stuff( (select ',' + cast(t.id as varchar(max))
from tabel t
for xml path ('')
), 1, 1, ''
);
The only purpose of stuff() is to remove the initial comma. The work is being done by for xml path.
Note that for some characters, the values will be escaped when using FOR XML PATH, for example:
SELECT STUFF((SELECT ',' + V.String
FROM (VALUES('7 > 5'),('Salt & pepper'),('2
lines'))V(String)
FOR XML PATH('')),1,1,'');
This returns the string below:
7 > 5,Salt & pepper,2
lines'
This is unlikely desired. You can get around this using TYPE and then getting the value of the XML:
SELECT STUFF((SELECT ',' + V.String
FROM (VALUES('7 > 5'),('Salt & pepper'),('2
lines'))V(String)
FOR XML PATH(''),TYPE).value('(./text())[1]','varchar(MAX)'),1,1,'');
This returns the string below:
7 > 5,Salt & pepper,2
lines
This would replicate the behaviour of the following:
SELECT STRING_AGG(V.String,',')
FROM VALUES('7 > 5'),('Salt & pepper'),('2
lines'))V(String);
Of course, there might be times where you want to group the data, which the above doesn't demonstrate. To achieve this you would need to use a correlated subquery. Take the following sample data:
CREATE TABLE dbo.MyTable (ID int IDENTITY(1,1),
GroupID int,
SomeCharacter char(1));
INSERT INTO dbo.MyTable (GroupID, SomeCharacter)
VALUES (1,'A'), (1,'B'), (1,'D'),
(2,'C'), (2,NULL), (2,'Z');
From this wanted the below results:
GroupID
Characters
1
A,B,D
2
C,Z
To achieve this you would need to do something like this:
SELECT MT.GroupID,
STUFF((SELECT ',' + sq.SomeCharacter
FROM dbo.MyTable sq
WHERE sq.GroupID = MT.GroupID --This is your correlated join and should be on the same columns as your GROUP BY
--You "JOIN" on the columns that would have been in the PARTITION BY
FOR XML PATH(''),TYPE).value('(./text())[1]','varchar(MAX)'),1,1,'')
FROM dbo.MyTable MT
GROUP BY MT.GroupID; --I use GROUP BY rather than DISTINCT as we are technically aggregating here
So, if you were grouping on 2 columns, then you would have 2 clauses your sub query's WHERE: WHERE MT.SomeColumn = sq.SomeColumn AND MT.AnotherColumn = sq.AnotherColumn, and your outer GROUP BY would be GROUP BY MT.SomeColumn, MT.AnotherColumn.
Finally, let's add an ORDER BY into this, which you also define in the subquery. Let's, for example, assume you wanted to sort the data by the value of the ID descending in the string aggregation:
SELECT MT.GroupID,
STUFF((SELECT ',' + sq.SomeCharacter
FROM dbo.MyTable sq
WHERE sq.GroupID = MT.GroupID
ORDER BY sq.ID DESC --This is identical to the ORDER BY you would have in your OVER clause
FOR XML PATH(''),TYPE).value('(./text())[1]','varchar(MAX)'),1,1,'')
FROM dbo.MyTable MT
GROUP BY MT.GroupID;
For would produce the following results:
GroupID
Characters
1
D,B,A
2
Z,C
Unsurprisingly, this will never be as efficient as a STRING_AGG, due to having the reference the table multiple times (if you need to perform multiple aggregations, then you need multiple sub queries), but a well indexed table will greatly help the RDBMS. If performance really is a problem, because you're doing multiple string aggregations in a single query, then I would either suggest you need to reconsider if you need the aggregation, or it's about time you conisidered upgrading.
This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Closed 6 years ago.
I am new to writing SQL scripts (at least anything more than SELECT * FROM X). I have run into a problem grouping a table by one value, and then joining values from another column into a single string.
I would like to perform a group by on a temp table, and then concatenate values of a column in the group together.
The table variable (edit), #categoriesToAdd, data structure is [SubscriberId int, CategoryId int].
What I am trying to do is something like (My understanding is that CONCAT is the bit missing from MSSQL):
SELECT SubscriberId,
CONCAT(CONVERT(VARCHAR(10), CategoryId) + ', ') as categoriesAdded
FROM #categoriesToAdd
GROUP BY SubscriberId
The concatenated category IDs for each subscriber would then look something like:
0001, 0002, 0003, 0004
Thanks!
In sql server you can use FOR XML PATH
select SubscriberId,
categoriesAdded=Stuff((SELECT ',' + CAST(CategoryId as VARCHAR(255)) FROM catsToAdd t1 WHERE t1.SubscriberId=#categoriesToAdd.SubscriberId
FOR XML PATH (''))
, 1, 1, '' )
from #categoriesToAdd as catsToAdd
GROUP BY SubscriberId
This question already has answers here:
How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field? [duplicate]
(13 answers)
Closed 7 years ago.
If I issue SELECT ID FROM TestAhmet I get this result:
1
3
5
2
4
but what I really need is one row with all the values separated by comma, like this:
1,2,3,4,5
How do I do this?
ps: I cant do this : Convert multiple rows into one with comma as separator
If id is numeric column then do like this
select stuff((select ',' +Convert(varchar(50),id)
from TestAhmet
for xml path ('')
), 1, 1, '') as users
This should work:
select stuff((select ',' + cast(id as varchar(8000))
from TestAhmet
for xml path ('')
), 1, 1, '') as users
This is a variation on the string aggregation logic often used in SQL Server. But, without a group by, you probably won't find many examples on the web.
This question already has answers here:
Simulating group_concat MySQL function in Microsoft SQL Server 2005?
(12 answers)
Closed 8 years ago.
My aim is to display the person name and all the reason for his absences(concated and displaying in a string).
I am using the following query to display the EmployeeName, ReasonForAbsence. I am having problem with concatenating and Displaying all record specific column called 'AbsenceReason'. The error is Incorrect Syntax near ='. More info about error- its happening for displaying absence reason part.
SELECT
--Displaying Name,
EMP.NAME,
--Displaying Absence Reason
(
SELECT
#AbsenceReasons= #AbsenceReasons + ';' + REASONTEXT
FROM
ABSENCE
WHERE ID=EMP.ID
)
FROM
(
SELECT
*
FROM
Employees
) EMP
What have I missed?
Thank you
As Martin says this is a duplicated question but...
SELECT DISTINCT Absence.EmpId, Reasons.AllReasons
FROM Absence
CROSS APPLY ( SELECT ReasonText + ' ,'
FROM Absence EMP2
WHERE EMP2.EmpId= Absence.EmpId
FOR XML PATH('')
) Reasons ( AllReasons)