So I have this MySQL query which I'm trying to create in SQL Server.
In MySQL I just use the function GROUP_CONCAT
and in SQL Server I want to use STUFF
.
MySQL
SELECT
GROUP_CONCAT(id
ORDER BY id DESC SEPARATOR '\', \'') AS id_list
FROM
testjob
WHERE
testjob.id IN (SELECT
MAX(testjob.id) AS id
FROM
testjob
INNER JOIN
target ON testjob.id = target.TestJobId
LEFT JOIN
dashboard_hidden ON testjob.TestSuiteCollectionId = dashboard_hidden.TestSuiteCollectionId
INNER JOIN
versions ON target.id = versions.TargetId
WHERE
target.Project = 'GiM1_0'
AND testjob.Finished != 'PENDING'
AND versions.Version IN ('V01.09.00.00110')
AND IFNULL(dashboard_hidden.Hidden, 0) != 1
GROUP BY testjob.id)
GROUP BY testjob.TestSuiteCollectionId DESC
I've tried to create the same in SQL Server using STUFF
(I'm running MSSQL 2014, so cant use STRING_AGG
)
SELECT
id_list =
COALESCE(STUFF((
SELECT '','' + CONVERT(VARCHAR(MAX), tj.id)
FOR XML PATH('')
), 1, 1, ''), '')
FROM
[SwMetrics].[testreportingdebug].testjob tj
WHERE
tj.id IN (SELECT
MAX(tj.id) AS id
FROM
[SwMetrics].[testreportingdebug].testjob tj
INNER JOIN
[SwMetrics].[testreportingdebug].target tg ON tj.id = tg.TestJobId
LEFT JOIN
[SwMetrics].[testreportingdebug].dashboard_hidden dash ON tj.TestSuiteCollectionId = dash.TestSuiteCollectionId
INNER JOIN
[SwMetrics].[testreportingdebug].versions v ON tg.id = v.TargetId
WHERE
tg.Project = 'GiM1_0'
AND tj.Finished != 'PENDING'
AND v.Version IN ('V01.09.00.00110')
AND ISNULL(dash.Hidden, 0) != 1
GROUP BY tj.id)
GROUP BY tj.TestSuiteCollectionId
ORDER BY tj.TestSuiteCollectionId DESC
When I run this I get this error:
Msg 8120, Level 16, State 1, Line 4 Column 'SwMetrics.testreportingdebug.testjob.id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
The reason I GROUP BY testjob.TestSuiteCollectionId
is because TestSuiteCollectionId
have multiple IDs which is the same, but the id
is unique and I want all those as a string. In this image you can see a MySQL with TestSuiteCollectionId
and the grouped id
s
Table without grouping:
#TestSuiteCollectionId, id
272, 37047
272, 36939
276, 37121
276, 36930
276, 37024
277, 37118
277, 37006
420, 37093
420, 36929
420, 37019
421, 37089
421, 36999
422, 37113
422, 37008
437, 37017
438, 37013
439, 37021