在stackoverflow的另一位开发人员的帮助下,我设法使用他的查询来创建一个代码,该代码根据groupid分组返回数据并返回为json
尝试使用以下概念:
插入数据:
CREATE TABLE some_table (some_data VARCHAR(20), some_other_data VARCHAR(20), groupId VARCHAR(20));
INSERT INTO some_table (some_data, some_other_data, groupId) values ('a', '1', 'id1');
INSERT INTO some_table (some_data, some_other_data, groupId) values ('b', '2', 'id1');
INSERT INTO some_table (some_data, some_other_data, groupId) values ('c', '3', 'id2');
执行查询:
SELECT '{"' + t.groupId + '": [{' + STUFF(
(
SELECT '{ "some_data":"' + td.some_data + '"', ', "some_other_data":' + td.some_other_data + '},'
FROM some_table td
WHERE t.groupId = td.groupId
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ']}'
FROM some_table t
GROUP BY t.groupId
结果:
{"id1": [{ "some_data":"a", "some_other_data":1},{ "some_data":"b","some_other_data":2},]}
{"id2": [{ "some_data":"c","some_other_data":3},]}
小提琴:
http://sqlfiddle.com/#!6/66b19/35
但我运行这个我看到一个错误
Error SQL Server Database Error: Conversion failed when converting the varchar value '{"' to data type int. 4 0
答案 0 :(得分:0)
可以找到Jason数组格式here
查看链接中的示例,您可以看到您有额外的支撑和额外的昏迷。
解决方案:
将[operation start];
(昏迷)从,
移至+ '},'
删除额外的大括号:',{ "some_data":"
- > '": [{' + STUFF(
<强>更新强>
非varchar列需要转换为'": [' + STUFF(
:(N)VARCHAR
最终查询:
CONVERT( NVARCHAR, [field] )
P.S。看起来像https://stackoverflow.com/a/45427001/6305294只是用括号
打了一个错字答案 1 :(得分:0)
如果您使用的是MSSQL 2016:
void insertard(void)
{
P=CAB;/* very first execution of this method P=NULL */
AUX=(struct lista *)malloc(sizeof(struct lista));
system("cls");
printf("INGRESE UN NUMERO ENTERO:");
scanf("%d",&AUX->info);
AUX->sig=CAB;
AUX->ant=CAB;
F=AUX;
if(CAB==NULL){
CAB=AUX;
P = AUX;/*first execution of this method P is no longer NULL but P is pointing to AUX */
}else{ //ESTO SI
while (P->sig!=CAB){
P=P->sig;
}
P->sig=AUX;
AUX->ant=P;
AUX->sig=CAB;
}
您可以找到文档https://docs.microsoft.com/en-us/sql/relational-databases/json/json-data-sql-server