My current SQL query is
INSERT INTO JobLocations(JobLocationId, JobId, DeviceId)
SELECT
((SELECT MAX(JobLocationId) FROM JobLocations) +
ROW_NUMBER() OVER (ORDER BY jh.GroupId)),
jh.GroupId,
MAX(jh.SerialNumber)
FROM
JobsHistory jh
INNER JOIN
dbo.Devices d ON jh.SerialNumber = d.DeviceId
GROUP BY
jh.GroupId
ORDER BY
jh.GroupId ASC
But the issue with this code is that it is entering ONLY the maximum value for jh.SerialNumber
whereas I want to enter ALL the values in jh.SerialNumber
. However, when I remove the MAX()
surrounding jh.SerialNumber
, I receive the following error:
Column 'JobsHistory.SerialNumber' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
So is there a simple way for me to inset all the SerialNumbers? I understand the error is happening because it does not know "which" SerialNumber to select and I've looked up this question in past posts like this but it doesn't explain how to just insert ALL the entries and rather inserts only the MAX value.
EDIT: example:
JobsHistory:
GroupId | SerialNumber
--------+--------------
2732 335890264
2732 335890261
2732 335890437
2732 335890438
It would only insert 335890438 instead of all 4