see the following code,
function queryData(tx) {
tx.executeSql('select sum(income) from balancesheet where id=1',
[],
rowsDataHandle,
errorCB);
}
rowsDataHandler = function(tx, results) {
var row = results.rows.item(0).income;
document.getElementById("mydata").innerHTML = 'Your Total income:\t'+ row;
};
income is an integer field.
please check the query as well. and how to get sum of all income transactions.
Try using an alias for the sum:
select sum(income) as totalincome from balancesheet where id=1
and then...
rowsDataHandler = function(tx, results) {
var row = results.rows.item(0).totalincome;
document.getElementById("mydata").innerHTML = 'Your Total income:\t'+ row;
}
Related
I have documents in my db that look like this:
{
"id": "1"
"entityType": "node"
"childNodes": [
{
"id": "2"
"entityType": "node"
"childNodes": [
...
]
}
]
}
As a large tree structure.
I'd like to count the total number of documents and subdocuments in my collection that are of entityType = "Node".
My attempt is to get the data one level at a time manually:
SELECT VALUE COUNT(c.id) FROM c where CONTAINS(c.id, 'a|') and c.entityType = 'node'
SELECT VALUE COUNT(l.id) FROM c JOIN l in c.childNodes where CONTAINS(c.id, 'a|') and c.entityType = 'node'
SELECT VALUE COUNT(l2.id) FROM c JOIN l in c.childNodes JOIN l2 in l.childNodes where CONTAINS(c.id, 'a|') and c.entityType = 'node'
First of all, it's hard to find a smooth(direct) way to implement your needs.Surely,the manual way you mentioned in your question works.However,if you have too many layers of JSON nesting, or it's random,your way maybe inappropriate.
I would suggest you loop the result recursively to get the count of objects which contains "entityType": "node".For example, in the cosmos db stored procedure:
function sample(prefix) {
var collection = getContext().getCollection();
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT c.childNodes FROM c where c.entityType = "node"',
function (err, feed, options) {
if (err) throw err;
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
var response = getContext().getResponse();
var count = {count:1};
loopChildNodes(feed,count);
response.setBody(count);
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
function loopChildNodes(array,count){
for (var i=0;i<array.length;i++){
console.log(count)
if(array[i].entityType == "node"){
count.count++;
}
if(array[i].childNodes!=null)
loopChildNodes(array[i].childNodes,count)
}
}
}
My test data:
Output:
FMDB seems to have lots of functions to deal with columns but none for rows. All I am trying to do is find the number of rows in a table.
func getTableRows() {
sharedInstance.database!.open()
let sqlStatement = "SELECT COUNT(*) FROM NAMESTABLE"
var resultSet: FMResultSet! = sharedInstance.database!.executeQuery(sqlStatement, withArgumentsInArray: nil)
if (resultSet != nil) {
let rowCount = XXXX
NSLog("Table Rows = %i",rowCount)
}
sharedInstance.database!.close()
}
I have tried various approaches with the XXXX but no joy. Am I going about this the wrong way? Many thanks.
try this:
func getTableRows() {
sharedInstance.database!.open()
let sqlStatement = "SELECT COUNT(field) FROM table_name"
var resultSet: FMResultSet! = sharedInstance.database!.executeQuery(sqlStatement, withArgumentsInArray: nil)
if (resultSet != nil) {
let rowCount = XXXX
NSLog("Table Rows = %i",rowCount)
}
sharedInstance.database!.close()
}
I'm building a Cordova app that's using the "Brodysoft SQLitePlugin".
When I insert an entry into safe_sex_planner_version and get the last inserted ID using results.insertId, it prints out without a problem. But when I try using that as foreign key in safe_sex_planner_entry as version_id, it's either not saving, or saving as a null.
Any help is much appreciated.
Thanks,
Zee
-- code below --
createNewVersion: function(questions)
{
var name = $("#plan-name-container #plan-name").val();
var last_insert_id = null;
db.transaction(function(tx){
var sql = "INSERT INTO safe_sex_planner_version (name) VALUES (?)";
tx.executeSql(sql, [name], function(tx, results){
last_insert_id = results.insertId;
console.log("Last inserted ID: " + last_insert_id);
}, errorCB);
}, errorCB, successCB);
db.transaction(function(tx){
for (var i = 0; i < questions.length; i++) {
question_id = questions[i].value;
var answer = $("#planner-items #question-" + question_id).find(".answer-field").val();
console.log("Answer: " + answer + "-1");
console.log("Last inserted ID: " + last_insert_id);
var sql = "INSERT OR REPLACE INTO safe_sex_planner_entry (version_id, question_id, answer) VALUES (?, ?, ?)";
// var sql = "INSERT INTO safe_sex_planner_entry (version_id, question_id, answer) VALUES (?, ?, ?)";
tx.executeSql(sql,[last_insert_id, question_id, answer], function(tx, res){}, errorCB);
}
var sql = "SELECT * FROM safe_sex_planner_entry WHERE version_id=?";
tx.executeSql(sql, [last_insert_id], function(tx, results) {
var len = results.rows.length;
console.log("Length of safe_sex_planner_entry: " + len);
for (var i = 1; i <= len; i++)
{
var record = results.rows.item(i);
console.log("Safe sex planner ID: " + record.id);
console.log("Safe sex planner Version ID: " + record.version_id);
console.log("Safe sex planner Question ID: " + record.question_id);
console.log("Safe sex planner Answer: " + record.answer);
}
});
var sql = "SELECT * FROM safe_sex_planner_entry";
tx.executeSql(sql, [], function(tx, results) {
var len = results.rows.length;
console.log("Length of safe_sex_planner_entry" + len);
});
}, errorCB, successCB);
}
It does not make sense to have the INSERTs in two different transactions (and functions).
Put everything into a single transaction, and do the insertion of the entries in the success callback of the first insert.
I've a problem with the following function. Its just the join I think. By using sql statement "SELECT * FROM pkw", I got the results. Both tables are filled with data.
Do you see the mistake?
function gotoauftrag(id) {
db = window.sqlitePlugin.openDatabase(shortName, version, displayName,maxSize);
var list = '';
var sql = "SELECT DISTINCT p.name FROM pkw p INNER JOIN ta_pkw tp ON tp.pkw_id = p.pkw_id AND tp.ta_id = ?";
db.transaction(function (tx) {
tx.executeSql(sql, [id], function (tx, results) {
if (results.rows.length > 0) {
document.getElementById('auftrag_pkw').innerHTML = '';
for (i = 0; i < results.rows.length; i++) {
r = results.rows.item(i);
list = '<li>'+r['name']+'<span class="ui-li-count">1</span></li>';
document.getElementById('auftrag_pkw').innerHTML += list;
$('#auftrag_pkw').listview('refresh');
}
}
});
});
$('#auftrag_pkw').listview('refresh');
}
I don't believe you are able to bind to the JOIN predicate. Try using the WHERE clause instead.
SELECT DISTINCT
p.name
FROM pkw p
INNER JOIN ta_pkw tp
ON tp.pkw_id = p.pkw_id
WHERE
tp.ta_id = ?
Also, you probably should be doing the ta_id selection before your join. The above will do a natural join on pkw_id, THEN it will filter the results based on ta_id.
this.db.transaction(function (tx)
{
tx.executeSql('SELECT tsk.*, cont.firstName, cont.lastName ,cont1.firstName, cont1.lastName, list.listId FROM tbl_tasks tsk, tbl_contacts cont,tbl_contactequests cont1, tbl_lists list WHERE (tsk.assignedId=0 or tsk.assignedId=cont.contactId or tsk.assignedId=cont1.contactRequestId) and tsk.taskCategoryType != "INBOX_NOT_ACCEPTED" and list.listId=tsk.listId and list.listId='+window.defaultlistid+' group by tsk.taskId', [], enyo.bind(this,this.queryResponse), enyo.bind(this,this.errorHandler));//call queryResponse
}.bind(this));
Now as you can see cont.firstName (Table tbl_contacts) & cont1.firstName has (Table tbl_contactequests) has same fields first name
for (var i = 0; i < len; i++)
{
list[i] = results.rows.item(i);
fname = list[i].firstName;
lname = list[i].lastName;
fullname = fname+' '+lname;
//alert(fullname);
if(list[i].assignedId==0)
{list[i].name = '';}
else
{list[i].name=fullname;}
}
with this loop i can able to featch first value of tbl_contacts field firstname.Now suppose if i can't to access tbl_contactequests table firstname.
Use AS keyword for SQL query:
'SELECT tsk.*,
cont.firstName AS cFirstName,
cont.lastName ,
cont1.firstName AS c1FirstName,
cont1.lastName, list.listId
FROM tbl_tasks tsk, tbl_contacts cont,
tbl_contactequests cont1, tbl_lists list
WHERE (tsk.assignedId=0 OR tsk.assignedId=cont.contactId OR
tsk.assignedId=cont1.contactRequestId) AND
tsk.taskCategoryType != "INBOX_NOT_ACCEPTED" AND
list.listId=tsk.listId AND list.listId='+window.defaultlistid+'
GROUP BY tsk.taskId'