0

我需要按字典中的值对结果进行排序,该字典以 JSON 形式存储在我的表中,等于一个参数。为了得到它,我在我的订单上使用大小写来检查字典中的值是否与参数匹配。订购表格后,我需要区分结果,但是我遇到了一个错误,我无法弄清楚。

这是我的查询:

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'))
4

1 回答 1

0

当您DISTINCT遍历结果集时,您实际上是在使用GROUP BY所有列。所以X.Value当你到达ORDER BY.

使用DISTINCT通常是一种代码味道,它表明连接没有被考虑过。在这种情况下,您可能应该将其OPENJSON放在子查询中SELECT TOP (1),尽管没有样本数据和预期结果很难说。

select
  item.*
from Items as items
outer apply (
    select top (1)
      X.[Key],
      X.Value
    from openjson(Data, '$.itemOrderPerGroup')
      with (
          [Key] int,
          Value int
      ) as X
) X
where items.ItemID in (select ItemID from @FilteredItemIDs )
order by case
    when @CurrentGroupID != 0 and X.Key = @CurrentGroupID then 1
    else 2 end,
    X.[Value];

请注意正确使用OPENJSONJSON 路径和属性名称。

如果您真正想要的是过滤OPENJSON结果,而不是按它们排序,那么您可以在EXISTS

select
  item.*
from Items as items
outer apply  X
where items.ItemID in (select ItemID from @FilteredItemIDs )
  and exists (select 1
    from openjson(Data, '$.itemOrderPerGroup')
      with (
          [Key] int,
          Value int
      ) as X
    where @CurrentGroupID = 0 or X.Key = @CurrentGroupID
);
于 2021-12-06T10:49:22.173 回答