Closed. This question needs details or clarity . It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post .
Closed yesterday.
Improve this question
I have the following database table data:
I must write SQL Server stored procedure to fetch the following output data:
Here the column Data
has the JSON data. We need to fetch only those data with the same BatchId
more than once. We need one entry for the same BatchId
with the Earliest Timestamp
.
I created the following temp table in the procedure with the query:
SELECT
JSON_VALUE(a.Data, '$.BatchId') BatchID,
COUNT(JSON_VALUE(a.Data, '$.BatchId')) AS BatchIDCount,
a.Name
INTO
#BULKDOCUMENT
FROM
Table1 a
GROUP BY
JSON_VALUE(a.Data, '$.BatchId'), a.Name
HAVING
COUNT(JSON_VALUE(a.Data, '$.BatchId')) > 1
Which returns the following output:
Can you please help me with how I can return the required data from the SQL Server stored procedure?
2条答案
按热度按时间iklwldmw1#
Create a stored procedure, something like-
Execute this sp using -
EXEC GetBulkData;
t2a7ltrp2#
You didn't specify what exactly you needed help with. I'm assuming you're struggling with how to do the aggregation where the grouped row only has values from the earliest row in the group.
You need to use a window function and sort the rows by batch ID.
I used the
json_object
function to stitch the fields together into a JSON document. I used thecount
androw_number
window functions to do the aggregation.