SQL服务器:是否可以在GROUP_BY内使用JSON_VALUE?

SQL Server: is it possible to use JSON_VALUE within GROUP_BY?

我试图在 GROUP_BY 子句中使用 JSON_VALUE 并收到此错误:

JSON text is not properly formatted. Unexpected character 'b' is found at position 0.

当我只在SELECT中使用它时,我得到了预期的结果。

SELECT 
    COUNT(*),
    Date,
    JSON_VALUE(msg, '$.a')
FROM
    requests
GROUP BY 
    Date, JSON_VALUE(msg, '$.a')

msg 列中似乎存储了无效的 JSON。但是你可以尝试改变你的说法。

Table:

CREATE TABLE requests (
   [Date] date,
   [Msg] nvarchar(1000)
)
INSERT INTO requests ([Date], [Msg])
VALUES
   ('20201020', N'{"m":"GET","a":"/Login.aspx"}'),
   ('20201020', N'{"m":"GET","a":"/Login.aspx"}'),
   ('20201020', N'{"m":"GET","a":"/Login.aspx"}'),
   ('20201021', N'{"m":"GET","a":"/Login.aspx"}'),
   ('20201021', N'{b:"GET","a":"/Login.aspx"} ')

声明:

SELECT 
   COUNT(*) AS [Count], 
   [Date], 
   CASE WHEN ISJSON([Msg]) = 1 THEN JSON_VALUE([Msg], '$.a') END AS Msg
FROM requests
GROUP BY [Date], CASE WHEN ISJSON([Msg]) = 1 THEN JSON_VALUE([Msg], '$.a') END

结果:

Count   Date        Msg
1       2020-10-21  
3       2020-10-20  /Login.aspx
1       2020-10-21  /Login.aspx

补充说明,如果要获取含有无效JSON内容的行,执行如下语句:

SELECT * 
FROM request 
WHERE ISJSON([Msg]) = 0