SQL 服务器查询分组错误

SQL Server query with group by a field error

我有以下 table MyTable:

 id │ value_two │ value_three │ value_four 
────┼───────────┼─────────────┼────────────
  1 │ a         │ A           │ AA
  2 │ a         │ A2          │ AA2
  3 │ b         │ A3          │ AA3
  4 │ a         │ A4          │ AA4
  5 │ b         │ A5          │ AA5

我想查询按 value_two 分组的对象数组 { value_three, value_four }value_two 应该单独出现在结果中。结果应如下所示:

 value_two │                                                                                    value_four                                                                                 
───────────┼───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
 a         │ [{"value_three":"A","value_four":"AA"}, {"value_three":"A2","value_four":"AA2"}, {"value_three":"A4","value_four":"AA4"}]
 b         │ [{"value_three":"A3","value_four":"AA3"}, {"value_three":"A5","value_four":"AA5"}]

在后期我可以这样做:

SELECT value_two
     , json_agg(row_to_json((value_three, value_four)::foo)) AS value_four
FROM   mytable
GROUP  BY value_two

但是在 SQL 服务器中我得到 'json_array_elements' is not a recognized built-in function name.

SQL SERVER 上与此等效的是什么。有人可以帮帮我吗?

如果您使用的是 SQL Server 2016+,您可以尝试使用 FOR JSON:

Table:

SELECT *
INTO Data
FROM (VALUES
   (1, 'a', 'A',  'AA'),
   (2, 'a', 'A2', 'AA2'),
   (3, 'b', 'A3', 'AA3'),
   (4, 'a', 'A4', 'AA4'),
   (5, 'b', 'A5', 'AA5')
) v (id, value_two, value_three, value_four)

声明:

SELECT DISTINCT d.value_two, j.value_four
FROM Data d
OUTER APPLY (
   SELECT value_three, value_four
   FROM Data
   WHERE value_two = d.value_two
   FOR JSON AUTO
) j (value_four)

结果:

value_two value_four
a         [{"value_three":"A","value_four":"AA"},{"value_three":"A2","value_four":"AA2"},{"value_three":"A4","value_four":"AA4"}]
b         [{"value_three":"A3","value_four":"AA3"},{"value_three":"A5","value_four":"AA5"}]