Dynamic group by query - mysql

I need to fire a dynamic group by query using an array.
a=['Branch','Company','Name'];
now , I need the query like
"select Branch,Company,Name,count(Name) as count from myTable group by Branch,Company,Name;"
Kindly suggest!!

Using your initial question data:
a=['Branch','Company','Name'];
function addCount(a) {
db.transaction(function (tx) {
str=a.join(", ");
tx.executeSql("select "+str+",count(*) as count from documentProperty GROUP BY "+str+";", [], function (tx, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
console.log(row);
}
}
});
});
}

Try this:
String quryString = "select Branch,Company,Name,count(Name) as count from myTable group by " ;
for (int i = 0; i < a.length; i++)
quryString =quryString +a[i];
now use quryString and fire your query.

Thanks Guys,
I tried and finally got my result from the following code.
jsonString=[{"field":"Branch"},{"field":"Company"},{"field":"Name"}]
function addCount(jsonString){
var a=[];
var str="";
$.each(jsonString,function (i,result){
a.push(result.field);
if(i == jsonString.length-1){
str += result.field;
} else{
str += result.field+",";
}
});
db.transaction(function (tx) {
var q=(a.length-1);
var query="select "+str+",count("+a[q]+") as count from documentProperty GROUP BY "+str+";"; console.log(query);
tx.executeSql(query, [], function (tx, result) {
if (result != null && result.rows != null) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
console.log(row);
}
}
});
});
}

Related

Compiling time takes too long

Here is my code:
function dataValidation()
{
var ss1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("2019년 출결 정보");
var ss2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("원생 정보");
var array = [];
for (var c = 0; c <= 1000; c++)
{
array[c] = [];
}
var count = 0;
var lastRow1;
var data1 = ss1.getRange("C:C").getValues();
for (var k = data1.length-1; k >= 0; k--)
{
if (data1[k][0] != null && data1[k][0] != '')
{
lastRow1 = k+1;
break;
}
}
var lastRow2;
var data2 = ss2.getRange("A:A").getValues();
for (var n = data2.length-1; n >=0; n--)
{
if (data2[n][0] != null && data2[n][0] != '')
{
lastRow2 = n+1;
break;
}
}
for (var i = 2; i <= lastRow1; i++)
{
for (var j = 2; j <= lastRow2; j++)
{
if (ss1.getRange(i, 3).getDisplayValue() == ss2.getRange(j, 1).getDisplayValue())
{
array[i-1][count] = ss2.getRange(j, 2).getDisplayValue();
count++;
}
}
var rule = SpreadsheetApp.newDataValidation().requireValueInList(array[i-1], true).setAllowInvalid(false).build();
ss1.getRange(i, 4).setDataValidation(rule);
count = 0;
}
}
I am so concerned because the compile speed takes too long... It takes about a minute to fully execute :(
Execution hint suggests to change from line 71:
for (var i = 2; i <= lastRow1; i++)
{
for (var j = 2; j <= lastRow2; j++)
{
if (ss1.getRange(i, 3).getDisplayValue() == ss2.getRange(j, 1).getDisplayValue())
{
array[i-1][count] = ss2.getRange(j, 2).getDisplayValue();
count++;
}
}
Personally I think this is because of nested loops but I don't have any clever ideas to replace this loops, nor I have much knowledge about google apps script.
What else I can do to decrease compile time?

Parsing MySql Query with Reserved Word

Below code is for getting sum of quantity from MySql database.
'deger' returns with {"SUM(quantity)":75}
I want to take '75' from that object.
I have tried;
deger.SUM(quantity)
Since SUM is reserved word, it does not work.
connection.query("SELECT SUM(quantity) FROM report WHERE fabrika = ? ", fabrika, function(err, rows) {
if (err) console.log(err);
else {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var deger = JSON.stringify(row)
console.log("**********************************");
console.log("Possible Quantity: " + deger); //Possible Quantity: {"SUM(Quantity)":75}
console.log("**********************************");
}
}
});
Thanks to #gview.
Adding 'as quantity' after SELECT, solved the problem.
connection.query("SELECT SUM(quantity) as quantity FROM report WHERE fabrika = ? ", fabrika, function(err, rows) {
if (err) console.log(err);
else {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var deger = JSON.stringify(row)
console.log("**********************************");
console.log("Possible Quantity: " + deger); //Possible Quantity: {"SUM(Quantity)":75}
console.log("**********************************");
}
}
});

MySQL query WHERE with object as result

I'm searching data.mesaj in mySQL query but connection is running cause query isn't running, what will do now also data.mesaj have, but I don't want this:
data = { mesaj: '\nHello', uid: 'mustafa' }
y=data.mesaj;
var row = [];
connection.query('select * from yapay_zeka where yapay_zeka.soru = y ', function (err, rows) {
if (err) {
console.log(err);
} else {
if (rows.length) {
for (var i = 0, len = rows.length; i < len; i++) {
row[i] = rows[i];
console.log(row);
}
}
}
connection.query("SELECT * from yapay_zeka WHERE yapay_zeka = '"+y+"'",
function(err, data) {});
connection.query("SELECT * from yapay_zeka WHERE yapay_zeka = '"+y+"'",
function(err, data) {});
I found it:
connection.query("select * from yapay_zeka where yapay_zeka.soru = ?',[data.mesaj]

Else if statement executes despite first condition is met

I have a patch of code that is intended to perform a search across a sheet then assign a variable if found.
Here's the code:
for(i=0;i<values.length; i++)
{
rowvalue = values[i];
for (j=l=1;j<rowvalue.length; j++) {
colvalue = rowvalue[j];
colvalue1 = colvalue.toString();
if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1
&& rowvalue[j+5] == "") {
rowp = i+1, colp = j+1;
var itemcode = 9;
}
else if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1) {
rowp = i+1, colp = j+1;
var itemcode = 9;
}
When executed, it will always return the value that met the 2nd condition(else if), despite the first condition was met. If I remove the else if statements, then I will get the correct return value.
As far as I know, once if statement was fulfilled, it's supposed to skip else or else if. But for some reason this wasn't the case in my situation. I'm not sure if I'm using the function properly or I'm misunderstanding on how the function work.
Try doing the same function this way:
if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1 )
{
if (rowvalue[j+5] == "")
{
rowp = i+1, colp = j+1;
var itemcode = 9;
}else{
rowp = i+1, colp = j+1;
var itemcode = 9;
}
}
If you indent your code correctly it becomes rather obvious where it goes wrong
Your code indented.
for(i=0;i<values.length; i++)
{
rowvalue = values[i];
for (j=l=1;j<rowvalue.length; j++)
{
colvalue = rowvalue[j];
colvalue1 = colvalue.toString();
if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1 && rowvalue[j+5] == "")
{
rowp = i+1, colp = j+1;
var itemcode = 9;
else if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1)
{
rowp = i+1, colp = j+1;
var itemcode = 9;
}
What you probably meant was to as below, please note the "Added missing closing curly bracket"
for(i=0;i<values.length; i++)
{
rowvalue = values[i];
for (j=l=1;j<rowvalue.length; j++)
{
colvalue = rowvalue[j];
colvalue1 = colvalue.toString();
if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1 && rowvalue[j+5] == "")
{
rowp = i+1, colp = j+1;
var itemcode = 9;
} // Added missing closing curly bracket
else if(colvalue1.indexOf("search1")>-1 && colvalue1.indexOf("search2")==-1)
{
rowp = i+1, colp = j+1;
var itemcode = 9;
}
}
}
single closing curly brace before the else statement should resolve the issue.

How to export (dump) WebSQL data

I'm working on a Chrome Extension that uses WebSQL to store historical data.
Being WebSQL, the DB is stored on the client.
I'd like to add an option to export/import such data so that the user can share/use this data with other users, or with other PCs.
These are my first steps on a client-only database, so I wonder how to do this.
I was thinking to convert the DB to a huge json string that the user can copy/paste but doesn't look very user-friendly.
Is there any better solution?
I got a single table dump solution working on a HTML5 database client I wrote a few days ago.
Check out http://html5db.desalasworks.com/script.js and scroll down to SqlClient.exportTable, this has an example that needs to be expanded to cover the whole database.
The steps are:
Step 1: Create the schema:
SELECT sql FROM sqlite_master
Step 2: Get a list of tables:
SELECT tbl_name from sqlite_master WHERE type = 'table'
Step 3: Loop through each of them and create an INSERT script with the results
transaction.executeSql("SELECT * FROM " + _tbl_name + ";", [],
function(transaction, results) {
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
var row = results.rows.item(i);
var _fields = [];
var _values = [];
for (col in row) {
_fields.push(col);
_values.push('"' + row[col] + '"');
}
_exportSql += ";\nINSERT INTO " + _tbl_name + "(" + _fields.join(",") + ") VALUES (" + _values.join(",") + ")";
}
}
}
);
Hope this is useful.
UPDATE JAN 2016 - WHOLE DB EXPORT
I've got a JS websqldump library that you can download from github as well.
This one will export the whole database. Check out the code on:
https://github.com/sdesalas/websqldump
Usage as follows
websqldump.export({
database: 'NorthwindLite',
success: function(sql) {alert(sql);}
});
Not the most elegant way, yet most convenient.
Just paste the script in chrome debugger tools then call c(), and you should get the file.
var looongSQL = "";
var x = function (options) {
if (options.n < options.sqlTables.length) {
onTheMove.openLocalDatabase().transaction(
function (tx) {
var sqlStatement = "SELECT * FROM " + options.sqlTables[options.n];
tx.executeSql(sqlStatement, [],
function (tx, rslt) {
if (rslt.rows) {
for (var m = 0; m < rslt.rows.length; m++) {
var dataRow = rslt.rows.item(m);
var _fields = [];
var _values = [];
for (col in dataRow) {
_fields.push(col);
_values.push('"' + dataRow[col] + '"');
}
looongSQL += "INSERT INTO " + options.sqlTables[options.n] + "(" + _fields.join(",") + ") VALUES (" + _values.join(",") + ");\n";
}
}
options.n++;
x(options);
}
);
});
}else
{
document.location = 'data:Application/octet-stream,' +
encodeURIComponent(looongSQL);
}
};
var c = function () {
onTheMove.openLocalDatabase().transaction(
function (transaction) {
transaction.executeSql("SELECT sql FROM sqlite_master;", [],
function (transaction, results) {
var sqlStatements = [];
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
console.log(results.rows.item(i));
var row = results.rows.item(i);
if (row.sql != null && row.sql.indexOf("CREATE TABLE ") != -1 && row.sql.indexOf("__") == -1) {
var tableName = row.sql.replace("CREATE TABLE ", "").split(/ |\(/)[0];
sqlStatements.push('DROP TABLE IF EXISTS ' + tableName);
}if(row.sql != null && row.sql.indexOf("__") == -1){
sqlStatements.push(row.sql);}
}
}
for (var j = 0; j < sqlStatements.length; j++) {
if (sqlStatements[j] != null) {
looongSQL += sqlStatements[j] + ';\r\n';
}
}
transaction.executeSql("SELECT tbl_name from sqlite_master WHERE type = 'table'", [],
function (transaction, res) {
var sqlTables = [];
for (var k = 0; k < res.rows.length; k++) {
if (res.rows.item(k).tbl_name.indexOf("__") == -1) {
sqlTables.push(res.rows.item(k).tbl_name);
}
}
x({
sqlTables: sqlTables,
n: 0
});
});
}
);
});
};
Another version that exports it as JSON
var looongSQL = "[\n";
var stringidiedLocalStorage = JSON.stringify(JSON.stringify(localStorage));
looongSQL += "/* 1 */ " + stringidiedLocalStorage + ",\n";
var x = function (options) {
if (options.n < options.sqlTables.length) {
onTheMove.openLocalDatabase().transaction(
function (tx) {
var sqlStatement = "SELECT * FROM " + options.sqlTables[options.n];
tx.executeSql(sqlStatement, [],
function (tx, rslt) {
if (rslt.rows && rslt.rows.length > 0) {
var _fields = [];
for (var col in rslt.rows.item(0)) {
_fields.push(col);
}
var insertTableSQL = "\"INSERT INTO " + options.sqlTables[options.n] + "(" + _fields.join(",") + ") ";
looongSQL += "/* " + options.count + " */ " + insertTableSQL;
for (var m = 0; m < rslt.rows.length; m++) {
var dataRow = rslt.rows.item(m);
var _values = [];
for (var col in dataRow) {
_values.push('\'' + dataRow[col] + '\'');
}
looongSQL += "SELECT " + _values.join(",");
if (m < rslt.rows.length - 1 && (m % 499 != 0 || m == 0)) {
looongSQL += " UNION ALL ";
}
if (m % 499 == 0 && m != 0) {
options.count++;
looongSQL += "\",\r\n/* " + options.count + " */ " + insertTableSQL;
}
}
looongSQL += "\",\r\n";
options.count++;
}
options.n++;
x(options);
}
);
});
} else {
looongSQL += ']';
document.location = 'data:Application/octet-stream,' +
encodeURIComponent(looongSQL);
}
};
var c = function () {
onTheMove.openLocalDatabase().transaction(
function (transaction) {
transaction.executeSql("SELECT sql FROM sqlite_master;", [],
function (transaction, results) {
var sqlStatements = [];
var count = 2;
if (results.rows) {
for (var i = 0; i < results.rows.length; i++) {
console.log(results.rows.item(i));
var row = results.rows.item(i);
if (row.sql != null && row.sql.indexOf("CREATE ") != -1) {
var objectType = row.sql.replace("CREATE ", "").split(/ |\(/)[0];
if (row.sql.indexOf("CREATE " + objectType + " ") != -1 && row.sql.indexOf("__") == -1) {
var objectName = row.sql.replace("CREATE " + objectType + " ", "").split(/ |\(/)[0];
sqlStatements.push('/* ' + count + ' */ "DROP ' + objectType + ' IF EXISTS ' + objectName + '"');
count++;
}
if (row.sql != null && row.sql.indexOf("__") == -1) {
sqlStatements.push('/* ' + count + ' */ "' + row.sql.replace(/(\r\n|\n|\r)/gm, " ") + '"');
count++;
}
}
}
}
for (var j = 0; j < sqlStatements.length; j++) {
if (sqlStatements[j] != null) {
looongSQL += sqlStatements[j] + ',\r\n';
}
}
transaction.executeSql("SELECT tbl_name from sqlite_master WHERE type = 'table'", [],
function (transaction, res) {
var sqlTables = [];
for (var k = 0; k < res.rows.length; k++) {
if (res.rows.item(k).tbl_name.indexOf("__") == -1) {
sqlTables.push(res.rows.item(k).tbl_name);
}
}
x({
sqlTables: sqlTables,
n: 0,
count: count
});
});
}
);
});
};