我正在努力处理一些 SQL,它应该将两个表中的数据连接在一起,但我还需要将 JSON 数组解析为输出表中的行......
以下是我想加入的 2 个表的示例:
命令
订单号 | 交货日期 |
---|---|
1 | 2020-05-18 07:00:00.000 |
2 | 2020-08-31 07:30:00.000 |
和历史:
订单号 | 历史_详情 |
---|---|
1 | [{"FieldName":"OrderStatusType.Description","FieldType":"String","ValueBefore":"Delivered","ValueAfter":"Undelivered","Action":2}] |
1 | [{"FieldName":"VoucherCode","FieldType":"String","ValueBefore":"","ValueAfter":"64646456","Action":1},{"FieldName":"PricingType.Description" ,"FieldType":"String","ValueBefore":"Standard","ValueAfter":"Discount","Action":2}] |
2 | [{"FieldName":"InitialComment","FieldType":"String","ValueBefore":"","ValueAfter":"Test Comment","Action":2},{"FieldName":"Appointment.Date ","FieldType":"DateTime","ValueBefore":"2020-08-06T07:30:00.000","ValueAfter":"2020-08-31T07:30:00.000","Action":0}] |
2 | 无效的 |
(不幸的是,字符串“null”,而不是 NULL - 我们在加入数据时必须处理)
我想要得到的是这样的输出:
订单号 | 交货日期 | 字段名 | 之前的价值 | 价值之后 |
---|---|---|---|---|
1 | 2020-05-18 07:00:00.000 | OrderStatusType.Description | 发表 | 未送达 |
1 | 2020-05-18 07:00:00.000 | 优惠券代码 | 64646456 | |
1 | 2020-05-18 07:00:00.000 | 定价类型.描述 | 标准 | 折扣 |
2 | 2020-08-31 07:30:00.000 | 初始评论 | 测试评论 | |
2 | 2020-08-31 07:30:00.000 | 约会日期 | 2020-08-06T07:30:00.000 | 2020-08-31T07:30:00.000 |
我可以自己做这两个查询,我只是在努力加入他们......
即,这给了我一切,而没有分解 JSON:
SELECT
o.order_number as [Order Number],
o.delivery_date as [Delivery Date],
oh.history_details as [History]
FROM [dbo].[Order] o
JOIN [dbo].[History] oh on oh.order_number = o.order_number
WHERE oh.history_details != 'null'
虽然我可以像这样进行 JSON 映射:
DECLARE @json NVARCHAR(MAX)
SET @json='[{"FieldName":"VoucherCode","FieldType":"String","ValueBefore":"","ValueAfter":"64646456","Action":1},{"FieldName":"PricingType.Description","FieldType":"String","ValueBefore":"Standard","ValueAfter":"Discount","Action":2}]';
SELECT *
FROM OPENJSON(@json)
WITH (
FieldName varchar(200) '$.FieldName' ,
ValueBefore varchar(200) '$.ValueBefore',
ValueAfter varchar(200) '$.ValueAfter'
)
我真的很难弄清楚如何将这两者结合在一起并获得我正在寻找的结果,很多 OPENJSON 示例就像我上面的示例一样,它们似乎期望单个列/数据类型。