I need to order my result by value from dictionary that stored as JSON in my table that equals a parameter. In order to get it I'm using case on my order by to check if the value from the dictionary match the parameter. After ordering the table I need to distinct the result however I'm getting an error and I couldn't figure it out.
here is my query:
declare @FilteredItemIDs -> temp table that filtered my items
declare @CurrentGroupID as int
select distinct item.*
from Items as items
outer apply openjson(json_query(Data, '$.itemOrderPerGroup'), '$') as X
where items.ItemID in (select ItemID from @FilteredItemIDs )
order by case
when @CurrentGroupID!= 0 and (JSON_VALUE(X.[Value], '$.Key') = @CurrentGroupID) then 1
else 2 end,
CONVERT(int, JSON_VALUE(X.[Value], '$.Value'))
When you
DISTINCTover a resultset, you are effectively usingGROUP BYover all columns. So theX.Valuedoesn't exist anymore when you get to theORDER BY.Using
DISTINCTis usually a code smell, it indicates that joins have not been thought through. In this case, you should probably place theOPENJSONinside a subquery, withSELECT TOP (1), although it's hard to say without sample data and expected results.Note the correct use of
OPENJSONwith a JSON path and property names.If what you actually want is to filter the
OPENJSONresults, rather than ordering by them, then you can do that in anEXISTS