您好,我是初学JSON的人,想问一个问题:
我的目标是尝试使结果看起来像这样:
{
"userid": "10293304" , "segments": ["Online_Flag"]
}
{
"userid": "10292298" , "segments": ["schedule_Appointment", "Enrolled_Order","Complete_Order"]
}
我可以使用 T-SQL 查询,使结果看起来像这样:
[{"userid":"10293159","segments":[{"segment":"Schedule_Appointment"}]},
{"userid":"10293056","segments":[{"segment":"Schedule_Appointment"}]},
{"userid":"10292838","segments":[{"segment":"Schedule_Appointment"}]},
问题在于我只需要显示JSON值(Schedule_Appointment),而不是键(segment)。
是否有任何方法(使用TSQL)可以隐藏键,仅在JSON数组中显示值?
我已经尝试查找使用SQL创建JSON数组的方法,但没有成功,如果有人能解释一下,我会非常感激。
SQL SERVER 2016
数据
CREATE TABLE [dbo].[Lotame_JSON](
[lead_id] [varchar](100) NULL,
[dist_date_key] [date] NULL,
[online_flag] [int] NULL,
[sched_appt_qty] [int] NULL,
[enroll_order_qty] [int] NULL,
[compl_order_qty] [int] NULL)
insert into [dbo].[Lotame_JSON]
values('105646','2016-12-1',1,0,0,1)
insert into [dbo].[Lotame_JSON]
values('125646','2016-12-1',0,0,1,0)
insert into [dbo].[Lotame_JSON]
values('112646','2016-12-1',0,1,1,0)
insert into [dbo].[Lotame_JSON]
values('106446','2016-12-1',0,0,1,0)
我的问题是:
select
[lead_id] AS 'userid',
(
SELECT segment
from
(
SELECT
CASE WHEN [online_flag] > 0 THEN '1' else null end as 'online_flag',
CASE WHEN sched_appt_qty > 0 THEN '2' else null end as 'Schedule_Appointment',
CASE WHEN enroll_order_qty > 0 THEN '3' else null end as 'Enrolled_Order',
CASE WHEN compl_order_qty > 0 THEN '4' else null end as 'Complete_Order'
FROM [dbo].[Lotame_JSON] as sub
WHERE sub.lead_id = main.lead_id
) t
UNPIVOT
(
segment1
for segment in (online_flag,Schedule_Appointment,Enrolled_Order,Complete_Order)
) as UnPvot
for JSON PATH
) AS 'segments'
from [dbo].[Lotame_JSON] as main
where online_flag = 0 and (sched_appt_qty > 0 or enroll_order_qty > 0 or compl_order_qty > 0)
and dist_date_key >= '2016-9-1'
FOR JSON PATH
谢谢
SQL SERVER
? - Pரதீப்