json 在SQL SELECT中使用多个参数进行筛选(比较)时,是否可以使用点导航?

qjp7pelc  于 2023-05-23  发布在  其他
关注(0)|答案(1)|浏览(154)

我在SQL中是新手,我只想检索某个groupID的记录,我使用这个查询:

SELECT @Date, Capacity, UserOrUserGroup 
FROM UCTimePhaseMonthly 
WHERE Date >= 2023-05-01 
  AND UserOrUserGroup.id = '/User/fdwr6cs6msxapw5zh4bh5jj93'

上面是一个返回对象的例子。

[
    {
        "id": "/UCTimePhaseMonthly/2z1r4vdk3d8qk16uegexx5rxx3453",
        "Date": "2023-06-01T00:00:00.0000000",
        "Capacity": {
            "unit": "Hours",
            "value": 176
        },
        "UserOrUserGroup": {
            "id": "/User/fdwr6cs6msxapw5zh4bh5jj93"
        }
    }    
 ]

如果字段id嵌套在UserOrUserGroup中,在SQL SELECT中使用多个参数进行筛选(比较)时,我可以使用点导航吗?

uujelgoq

uujelgoq1#

因为你有一个数组,你需要使用OPENJSON。您可以在EXISTS中执行此操作

SELECT
  @Date,
  tpm.Capacity,
  tpm.UserOrUserGroup
FROM UCTimePhaseMonthly tpm
WHERE Date >= '20230501'
  AND EXISTS (SELECT 1
    FROM OPENJSON(tpm.UserOrUserGroup)
      WITH (
        id varchar(100) '$.UserOrUserGroup.id'
      ) j
    WHERE j.id = '/User/fdwr6cs6msxapw5zh4bh5jj93'
);

或者你可以提取出实际值

SELECT
  @Date,
  tpm.Capacity,
  tpm.UserOrUserGroup,
  j.id
FROM UCTimePhaseMonthly tpm
CROSS APPLY OPENJSON(tpm.UserOrUserGroup)
WITH (
  id varchar(100) '$.UserOrUserGroup.id'
) j
WHERE Date >= '20230501'
  AND j.id = '/User/fdwr6cs6msxapw5zh4bh5jj93';

请注意,日期需要用引号括起来。

相关问题