Compare two SQL column values in Google Pie Chart - sql

Afternoon all, I'm trying to compare two SQL columns values against each to work out the percentage and then display this output in Google charts
I have the following query..
SELECT Count(lineAudited) as total_count, 121 as total_required FROM SMT_24_Point_Check.dbo.auditRecord which displays two columns, one value is 111 and the second column is 121, therefore the percentage is 91%, When I try to input this query into Google Chart, it's only displaying the second columns value
This displays two columns, one value is 111 and the second column is 121, therefore the percentage is 91%, When I try to input this query into Google Chsart, it's only displaying the second columns value
function drawChartCategory() {
var data = google.visualization.arrayToDataTable([
['total_count', 'total_required'],
<?php
while($row = odbc_fetch_array($result1))
{
echo "['".$row["total_count'"]."', ".$row["total_required"]."],";
}
?>
]);
var options = {
title: 'Total audits completed',
width: 900,
height: 500,
backgroundColor: '#E8E8E8',
pieSliceText: 'value',
is3D: true
};
var chart = new google.visualization.PieChart(document.getElementById('piechartCategory'));
chart.draw(data, options);
}
How can I get it to show a segment of 91% and 9%?

check the data format for a PieChart
there should be two columns for each row / slice.
first column should be a string for the name of the slice,
the second a number for the value.
as such, try formatting your data as follows...
'Required', 111
'Not Required', 10
you cannot add the total as a slice or it will throw off the percentage.
while($row = odbc_fetch_array($result1))
{
echo "['Required', ".$row["total_required"]."],";
echo "['Not Required', ".($row["total_count'"] - $row["total_required"])."],";
}

Related

How to update an certain row value using gota dataframe?

I'm trying to parse data from certain server, and need to export it to excel or csv.
before I export, I need to do some post processing such as merging values between parsed data.
for example,
There are two series out of all data.
series#1 - {Name: "MATH", Student:"Zay",Id:"MATH-123", Date:"12/25/2022", Status:"Good"}
series#2 - {Name: "MATH", Student:"Zay",Id:"MATH-124", Date:"12/26/2022", Status:"Bad"}
What I want to do is,
I want to update series#1's Status to
{Name: "MATH", Student:"Zay", Id:"MATH-123,MATH-124", Date:"12/25/2022,12/26/2022", Status:"Bad"}
Id, Date ==> combining with ","
Status ==> changing to latest result
Now I'm using Filter method of DataFrames,
type MyDataSet struct{
Name string
Student string
Id string
Date string
Status string
}
totalDF:=series1_result //overall result dataframe
df := dataframe.LoadStructs(series2_result) //new dataframe which needs to be compared to previous data `totalDF`
length := df.Nrow()
for i:=0;i<length;i++ {
name:=df.Subset(i).Col("Name")
student:=df.Subset(i).Col("Student")
query:= totalDF.Filter(
dataframe.F {
Colname:"Name",
Comparator:series.Eq,
Comparando:name,
},
).Filter(
dataframe.F {
Colname:"Student",
Comparator:series.Eq,
Comparando:student,
}
)
if query.Nrow()==0 {
totalDF = totalDF.Concat(df.Subset(i))
} else {
newDF:= dataframe.LoadStructs([]MyDataSet{
{
Name:query.Col("Name").String(),
Student:query.Col("Student").String(),
Id:query.Col("Id").String()+","+df.Subset(i).Col("Id").String(),
Date:query.Col("Date").String()+","+df.Subset(i).Col("Date").String(),
Status:df.Subset(i).Col("Status").String(),
}
})
query.Set(
series.Ints([]int{0}, newDF) //It's not updated as query was not an pointer
)
}
}
Even though I updated values on result of query, it's not updated on totalDF
How can I query the data from totalDF and update the data on that totalDF?
How can I get index number of Filtered item using Filter function?
Should I implement search function instead of using Filter function?
I would really appreciate it if you could help me.
Thanks everyone!
Merry Christmas!
*I tried to find out from official docs.
*But every method returns Value, not Pointer.

Multiple MySQL queries returning undefined when outputting value

I am running two database queries to retrieve data that I will outputting in a message embed. The queries are returning the proper rows when I just dump the entire result into the console. However, whenever I try to output the actual value for one of the rows, it displays as undefined in the message embed.
From what I've found based on examples, rows[0].somevalue should be outputting the correct results.
let mentionedUser = message.mentions.members.first();
let captainUser = client.users.find(user => user.id == `${mentionedUser.id}`);
con.query(`SELECT * FROM captains WHERE id = '${mentionedUser.id}';SELECT * FROM results WHERE captain = '${captainUser.username}'`, [2, 1], (err, rows) => {
if(err) throw err;
console.log(rows);
const infoEmbed = new Discord.RichEmbed()
.setColor("#1b56af")
.setAuthor('Captain Information', client.user.displayAvatarURL)
.setThumbnail('https://i.imgur.com/t3WuKqf.jpg')
.addField('Captain Name', `${mentionedUser}`, true)
.addField('Cap Space', `${rows[0].credits}`, true) // Returns undefined
message.channel.send(infoEmbed);
});
This is the console result
[ [ RowDataPacket {
id: '91580646270439424',
team_name: 'Resistance',
credits: 85,
roster_size: 2 } ],
[ RowDataPacket { id: 'Sniper0270', captain: 'BTW8892', credits: 10 },
RowDataPacket { id: 'Annex Chrispy', captain: 'BTW8892', credits: 5 } ] ]
In the code posted above, the expected output of rows[0].credits should output 85. No error codes are present, it just displayed as "undefined" in the message embed.
You are executing two queries inside a single query call. It looks like the mysql library returns an array of arrays in this scenario where the first value is the result of the first query and the second is the result of the second query. This is non standard. Normally you would either execute each query in its own query call or you would use a union to join the two queries into a single resultset.
this is not the practical way to send query request , as query is a single statement excluding the bulk update , you cannot execute two different query using a single con.query , it is not a proper way. execute them separately

morris.js displaying difficulties

I have a morris.js graph. I have a table with 3 columns id with values such as 1,2,3 etc, usernames with values such as sophie, nick, Paul etc and timesloggedin with values such as 69, 58, 4 etc.
I created a chart that has the ids on x and the timesloggedin on y.
What I want is instead of displaying the id number on the bottom of the chart under the bars, to have their usernames. You can see the chart here:
http://kleanthisg.work/chartsnew2.php
CODE:
http://kleanthisg.work/CODE.TXT
table:
user list:
You need to provide the username and set it as xkey
Morris.Bar({
element : 'chart_line_1',
data:[{ id:'1', timesloggedin:65, username: 'Paul'},
{ id:'5', timesloggedin:10, username: 'John'},
{ id:'7', timesloggedin:4, username: 'Steve' }],
xkey:'username',
ykeys:['timesloggedin'],
labels:['timesloggedin'],
hideHover:'auto',
});

Sorting by part of a number in datatables

I have a DataTable where my first column is a VIN number.
Example: FLXVU3822G1000013
Now VIN numbers are just a bunch of information tacked together. The last 6 numbers are the sequence number for that year. You can see that this example vehicle is the 13th one of the year. I'd really like to have my list filtered on those last 6 digits. Is there a way to do that?
You can easily solve this by a custom sorting plugin. In fact you just need to extract the last 6 digits and return them as a number, then dataTables will sort the column using the internal number sorting algorithm :
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"last-6-digits-pre": function ( a ) {
var n = a.substring(a.length - 6, a.length)
return parseInt(n)
}
})
Usage :
var table = $('#example').DataTable({
columnDefs : [
{ targets: 0, type: 'last-6-digits' }
]
})
where targets: 0 is the index of the column you want to be sorted this particular way.
See demo -> http://jsfiddle.net/zhmcLkb9/

Filter other columns based on first columns

I'm using jquery data tables and I'm assigning an array of values to the initialization of the data table. The table basically looks like this.
based on an an radio button I would like to limit the items that are display in the table and the items that are searched in the table.
For my example it would be based on the "Chart column". I want to limit the table to only show the items that are based on chart "D" or Chart "S". Here is how I'm initializing the table.
if (!$.fn.DataTable.isDataTable( '#fundLookUptbl' ) ) {
fundTable = $('#fundLookUptbl').DataTable( {
data: funds,
columns: [
{ "mData": "chart" },
{ "mData": "fund" },
{ "mData": "orgDefault" },
{ "mData": "progDefault" }
]
} );
var filteredData = fundTable
.columns( [0, 1] )
.data()
.eq( 0 )
.filter( function ( value, index ) {
return value = 'D' ? true : false;
} );
}
This is obviously not working, and the filterData variable is a lousy attempt on trying to make it work. I'm having a hard time understanding the API's. So the question is , How can initialize the table to only show the items that are based on a given chart. I know that I can remove the items of the array but i don't want to do that since I would simple like to be able to switch between chart "D" and "S" but still continue to search through the other columns.
I believe that filtering the column would solve your problem.
table.column(0).search('Bruno').draw()
So you could just filter the column when the radio button selection change
Here is a fiddle example
I´m not sure to be understanding what you want to do but here are some options:
One way is selecting by default value example "s". You can use a dropdown is easier to handled .Then select with jQuery the dafault value "s" on that dropdown and add a function
$("#DropdownId").change(function () {
var chart=$("#DropdownId").val();
});
$.ajax({
url: "url")",//url to reload page with new value
type: "POST",
data: {chart:chart},
success: function (data) {
}
});
});
on this way the filter is on backend. If you want to do something on the row depending of a column value you shoud to add something like this
"fnRowCallback": function (nRow, mData, iDisplayIndex, iDisplayIndexFull) {
if (mData["chart"] =="s") {
return nRow;
}
},
Datatables: custom function inside of fnRowCallback.
Good luck
fundTable.order( [0, 'asc'] );
Try that or look at this particular page for reference:
https://datatables.net/reference/api/order%28%29
Basically orders in pair of columnIndex in either asc(ending) or desc(ending) order.