I need to write a Linq query in a specific format for a json file. There are 3 tables in the Database.
Student, with Student Id and name.
Subject, with Subject Id and name.
Results with Student Id, Student Id, Result and Date of Result.
This is my Query to get Results
var studentQuery = (from c in db.Students
join f in db.Results
on c.ID equals f.StudentID
join d in db.Subjects
on f.SubjectID equals d.ID
where c.ID == Convert.ToInt32(DropDownList1.SelectedValue)
select new newResult{
ID = f.StudentID,
Date = convertDateToUTC(f.Date.Value),
Name = c.Name.Trim(),
Result1 = f.Result1.Value,
Type = d.Subject1.Trim()
})
.ToList();
return studentQuery;
But I wish to return the query in the
in the format below
[ { "name": "Denis P6 Results", "type": "English", "data": [ [ 1325431800000, 54 ], [ 1325691000000, 65 ], [ 1325950200000, 73 ], [ 1326209400000, 60 ] ] },
{ "name": "Denis P6 Results", "type": "Maths", "data": [ [ 1325518200000, 76 ], [ 1325777400000, 81 ], [ 1326036600000, 80 ], [ 1326295800000, 70 ] ] },
{ "name": "Denis P6 Results", "type": "Science", "data": [ [ 1325604600000, 80 ], [ 1325863800000, 75 ], [ 1326123000000, 69 ], [ 1326382200000, 68 ] ] },
{ "name": "Mak P6 Results", "type": "English", "data": [ [ 1325431800000, 57 ], [ 1325691000000, 49 ], [ 1325950200000, 66 ], [ 1326209400000, 70 ] ] },
{ "name": "Mak P6 Results", "type": "Maths", "data": [ [ 1325518200000, 80 ], [ 1325777400000, 83 ], [ 1326036600000, 85 ], [ 1326295800000, 79 ] ] },
{ "name": "Mak P6 Results", "type": "Science", "data": [ [ 1325604600000, 67 ], [ 1325863800000, 69 ], [ 1326123000000, 66 ], [ 1326382200000, 62 ] ] } ]
I really need some help as I've been searching for days. I am a total newbie at this.
Thanks for any help.
Let's break this down into each of the steps you're trying to achieve:
Group the results, by person and subject.
Render these into JSON.
For the first bit, we can do something like
var groupedResults = from result in db.Results
group result by new { result.StudentID, result.SubjectID } into grouping
select new { grouping.Key, grouping };
var resultsWithName = from result in groupedResults
join student in db.Students on result.Key.StudentID equals student.ID
join subject in db.Subjects on result.Key.SubjectID equals subject.ID
select new
{
result.Key,
student.Name,
subject.Type,
result.grouping
};
resultsWithName now contains a sequence of name and subject pairs, together with a sequence of the results. This is the first bit done.
You could use a library for generating the JSON, but this isn't too bad to do by hand:
var jsonRendered = resultsWithName.Select(g =>
string.Format("{{ \"name\" : \"{0} Results\", \"type\" : \"{1}\", \"data\" : {2} }}",
g.Name,
g.Type,
"[ " + string.Join(", ", g.grouping.Select(r => string.Format("[ {0}, {1} ]", r.Date, r.Mark))) + " ]"));
Here, we iterate over all the grouped results (i.e. for each person and each subject), then create a single string containing the results for that subject.
I haven't used quite the same names for some of the variables as you, but hopefully it's clear how to adapt this for your code.
JavaScriptSerializer serializer = new JavaScriptSerializer();
var json = serializer.Serialize(resultsWithName);
Just use the built in .NET json serializer. No need to make it too complicated.
Related
dslContext.select(
jsonObject(
key("id").value(CATEGORY.ID),
key("courses").value(
jsonArrayAgg(
jsonObject(
Arrays.stream(COURSE.fields())
.map(i -> key(CamelcaseConverter.snakeToCamel(i.getName())).value(
i))
.collect(
Collectors.toList())
)
)
)
)
).from(CATEGORY)
.leftJoin(COURSE_CATEGORY).on(CATEGORY.ID.eq(COURSE_CATEGORY.CATEGORY_ID))
.leftJoin(COURSE).on(COURSE.ID.eq(COURSE_CATEGORY.COURSE_ID)).fetchInto(JSONObject.class)
Output I got:
[
{
"courses": [
{
"id": 19
},
{
"id": null
}
],
"name": "Exam1",
"id": 1,
}
]
The required output is
[
{
"courses": [
{
"id": 19
}
],
"name": "Exam1",
"id": 1
},
{
"courses":[],
"name": "Exam2",
"id": 2
}
]
The query which need to be executed is
"select * from category left outer join course_category on category.id = course_category.category_id left outer join course on course_category.course_id = course.id"
how do I implement it?
You forgot to group by:
.groupBy(CATEGORY.ID, CATEGORY.NAME)
If you have a primary (or unique) key on CATEGORY.ID, then in MySQL, it will be sufficient to group by that
.groupBy(CATEGORY.ID)
Lets say this is my database table
id ProductID color size
1 abc red L
2 abc green M
3 abc yellow S
4 def purple L
5 def brown M
6 def pink S
Now I am fecthing data using my sql queires but in response i want my json in this structure
{
"status": true,
"message": "All Product Logs has been fetched Successfully",
"products": [
{
"id": "1",
"ProductID": "abc",
"colors": [
"red",
"green",
"yellow",
],
"sizes": [
"L",
"M",
"S",
]
},
{
"id": "2",
"ProductID": "def",
"colors": [
"purple",
"brown",
"pink",
],
"sizes": [
"L",
"M",
"S",
]
}
]
}
And this what i do but it doesn't makes sense
if ($response) {
$JSONDataArray=[];
$ColorDataArray=[];
$SizeDataArray=[];
while($row = mysqli_fetch_array($response)){
$ColorDataArray[]=array($row['color']);
$SizeDataArray[]=array($row['size']);
$JSONDataArray[]=array('productid' =>$row['productid'],'color' => $ColorDataArray,'sizes' => $SizeDataArray);
}
echo json_encode(['status'=>true,'message'=>'All Products has been fetched Successfully','products'=>$JSONDataArray]);
}
Anykind of help would be appreciated. What do u think should i change my database structure or should i change my query. I simply user Select * query without any where clause
One option is to use the JSON_ARRAYAGG function:
SELECT JSON_PRETTY(
CONCAT(
'{"status": true, ',
'"message": "All Product Logs has been fetched Successfully", ',
'"products": [',
(
SELECT
GROUP_CONCAT(`der`.`json`)
FROM (
SELECT
JSON_OBJECT(
'ProductID', `ProductID`,
'colors', JSON_ARRAYAGG(`color`),
'sizes', JSON_ARRAYAGG(`size`)
) `json`
FROM
`tbl`
GROUP BY
`ProductID`
) `der`
),
']}'
)
) `json_response`;
See dbfiddle.
Keep in mind: GROUP_CONCAT: The result is truncated to the maximum length that is given by the group_concat_max_len system variable.
I have just realised on my AWS Aurora postgres cluster having functions with temp_tables are not friendly with read replicas. I need to do a re-write (using CTEs) - anyway.... How do I take a json object with arrays nested and flatten them to a table like so:
{
"data": [
{
"groupName": "TeamA",
"groupCode": "12",
"subGroupCodes": [
"11"
]
},
{
"groupName": "TeamB",
"groupCode": "13",
"subGroupCodes": [
"15", "22"
]
}
]
}
I would like the output table to be:
groupName groupCode subGroupCodes
TeamA 12 11
TeamB 13 15
TeamB 13 22
I know I can get most of the way there with:
SELECT j."groupCode" as int, j."groupName" as pupilgroup_name
FROM json_to_recordset(p_in_filters->'data') j ("groupName" varchar(50), "groupCode" int)
But I just need to get the subGroupCodes as well but unpacking the array and joining to the correct parent groupCodes.
You need to first unnest the array, and then another unnest to get the subgroup codes:
with data (j) as (
values ('{
"data": [
{
"groupName": "TeamA",
"groupCode": "12",
"subGroupCodes": [
"11"
]
},
{
"groupName": "TeamB",
"groupCode": "13",
"subGroupCodes": [
"15", "22"
]
}
]
}'::jsonb)
)
select e ->> 'groupName' as group_name,
e ->> 'groupCode' as code,
sg.*
from data d
cross join lateral jsonb_array_elements(d.j -> 'data') as e(g)
cross join lateral jsonb_array_elements_text(g -> 'subGroupCodes') as sg(subgroup_code)
How to index (N1QL query in Couchbase) above document to speed up searching by SerialNumber field in nested array (doc => groups => items => item.SerialNumber)?
Sample:
{
"Id": "0012ed6e-41af-4e45-b53f-bac3b2eb0b82",
"Machine": "Machine2",
"Groups": [
{
"Id": "0fed9b14-fa38-e511-893a-001125665867",
"Name": "Name",
"Items": [
{
"Id": "64e69b14-fa38-e511-893a-001125665867",
"SerialNumber": "1504H365",
"Position": 73
},
{
"Id": "7be69b14-fa38-e511-893a-001125665867",
"SerialNumber": "1504H364",
"Position": 72
}
]
},
{
"Id": "0fed9b14-fa38-e511-893a-001125665867",
"Name": "Name",
"Items": [
{
"Id": "64e69b14-fa38-e511-893a-001125665867",
"SerialNumber": "1504H365",
"Position": 73
},
{
"Id": "7be69b14-fa38-e511-893a-001125665867",
"SerialNumber": "1504H364",
"Position": 72
}
]
}
]
}
my query:
CREATE INDEX idx_serial ON `aplikomp-bucket`
(ALL ARRAY(ALL ARRAY i.SerialNumber FOR i IN g.Items END ) FOR g In Groups END);
CREATE INDEX idx_serial ON `aplikomp-bucket` (DISTINCT ARRAY(DISTINCT ARRAY i.SerialNumber FOR i IN g.Items END ) FOR g In Groups END);
SELECT META().id FROM `aplikomp-bucket` AS a
WHERE ANY g IN a.Groups SATISFIES (ANY i IN g.Items SATISFIES i.SerialNumber > 123 END) END;
I converted the JSON string to Powershell in v5. The original json string is below:
$j = #'
[{
"id": "1",
"Members": [
"A",
"B",
"C"
]
}, {
"id": "2",
"Members": [
"A",
"C"
]
}, {
"id": "3",
"Members": [
"A",
"D"
]
}]
'#
$json = $j | ConvertFrom-Json
I would like the result set to look like the result set below. Eventually I will export to SQL:
id Members
----- --------
1 A
1 B
1 C
2 A
2 C
3 A
3 D
try this
$json | % {
$id = $_.id
$_.members | select #{n='id';e={$id}}, #{n='members';e={$_}}
}