Group by in sub query - android

Here's the table in question,
What I am trying to do is to get the count of entries segregated by type for each person(claimed_by). For example, for example,
John : Total entries :4 , Type 1 entries: 1, Type 2 entries : 3.
Jane : Total entries :4 , Type 1 entries: 4, Type 2 entries : 0.
Here's what I have at the moment,
SELECT count(id) as total_entry,claimed_by,
(select count(id) from tblIssues where type=1) as type1_entry,
(select count(id) from tblIssues where type=2) as type2_entry
FROM tblIssues
GROUP BY claimed_by
order by count(id) desc
This return correct value for total_entry but incorrect for type1 and type2. I think this is because I am not doing a group_by in the sub query but I am not sure how to correctly do that.

You can put a condition in the sum(). It adds up how many times it is true (1).
SELECT claimed_by,
count(id) as total_entry,
sum(type = 1) as type1_entry,
sum(type = 2) as type2_entry,
sum(type = 3) as type3_entry
FROM tblIssues
GROUP BY claimed_by
order by count(id) desc

Related

How to format Query using ROOM

So I have a table with 4 columns and would like to sum the values of the amount column where isExpense is true and where isExpense is false. I would like to subtract those 2 values and return that sum.
I don't have much experience with SQL other than single line queries so I'm struggling to format this.
#Query("""
SELECT SUM (amount) AS INCOME FROM `transaction` WHERE isExpense = 0,
SELECT SUM (amount) AS EXPENSE FROM `transaction` WHERE isExpense = 1,
SUM (INCOME - EXPENSE) AS BALANCE
""")
fun getTotalBalance(): Flow<Double>?
I could get around this by creating more columns in my table if all else fails.
Use case expressions to do conditional aggregation:
SELECT SUM(case when isExpense = 0 then amount else 0 end) AS INCOME,
SUM(case when isExpense = 1 then amount else 0 end) AS EXPENSE,
SUM(case when isExpense = 0 then amount
when isExpense = 1 then -amount
end) as BALANCE
FROM `transaction`
WHERE isExpense IN (0, 1) -- Not needed, but might speed things up if there
-- are other values than 0 and 1

Sqlite Trigger to Update table 1 when certain rows of table 2 is updated

I have two tables in sqlite in android:
Table1: Outlets
id pid OutletName Status
1 1 Tesco 1
2 1 Coors 1
3 2 Coors 1
Table2: projectparams
ppid projectname outletname param projStatus
1 RA_Pepsi Tesco shelfstrip 2
2 RA_Pepsi Tesco shelfleft 2
3 RA_Cocola Coors shelfstrip 1
Table1: For every PID (ProjectID) there are multiple Outlets stored in OutletName.
Table2: For each outlet there are multiple params stored in project params.
Whenever the user completes a task the param in Table2 is updated to 2. In the above example, when the user completes two tasks in Tesco, the status would be updated to 2 upon completion.
I am trying to set the outlets status to 2 based on completion of tasks for every outlet. In this example, when the status is updated to 2 in projectparam table, I want the Status in Outlets to be updated to 2 for the outlet Tesco.
I am using the following codes:
triggered when the task gets completed.
private void updateTaskStatus() {
SQLiteDatabase db = sqLiteHelper.getWritableDatabase();
String spinTextRecovered = spnTxt.getString("spinText", null);
String updateTable = "update projectparams set projStatus=2 where param='"+spinTextRecovered+"' and projectName='"+projectName+"' and OutletName='"+outletName+"'";
db.execSQL(updateTable);
takePicButton.setEnabled( false );
}
Triggered every time when the task gets completed and updates the outlet status when all the tasks for an outlet is completed.
private void updateOutletStatus() {
String query = "select OutletName from projectparams where projectName= '"+projectName+"' and OutletName= '"+outletName+"' group by projStatus";
if (sqLiteHelper.getData(query).getCount()==1) {
Toast.makeText( getApplicationContext(), "No more tasks in this outlet!", Toast.LENGTH_SHORT ).show();
SQLiteDatabase db = sqLiteHelper.getWritableDatabase();
String outletUpdate = "update outlets set Status=2 where OutletName='"+outletName+"' and pid = (select id from projects where ProjectName = '"+projectName+"' ) ";
db.execSQL(outletUpdate);
}
}
The above code works...however since I am using an intent to display the projects, outlets and task parameters, many times i find the updation of outlet not happening.
Can i write this better? Can someone guide me to use triggers?
I believe your core issue is that the query
String query = "select OutletName from projectparams where projectName= '"+projectName+"' and OutletName= '"+outletName+"' group by projStatus";
Will return 1 not only if all the projects have completed but also if none have been completed (i.e. all the projStatus values are 1).
Additionally, as it stands if very much appears that the Outlets table is superfluous. That is all columns (bar the id, which serves no purpose) are duplicated in the projectparams table.
You can ascertain is all the tasks for a project by multiplying the number of params by 2 (the status completion value) against the sum of all of the projstatus values. If they match then all params have been set to 2.
Consider the following which is your data (but status 1 for RA_Perpsi/Tesco rows) plus some additional data where the only fully completed is for the Completed Example project (highlighted) as per :-
The using (to process all results)
-- WHERE clause removed group by projectname added (to show all results)
SELECT OutletName FROM projectparams GROUP BY projectname,projStatus;
The result is :-
That is Ra_Pepsi/Tesco has no params completed (nothing done) but there is only one row so the project is detected as being completed. Likewise for RA_Cocola and for Some other outlet.
Completed Example produces 1 row so is complete as it should be. Incomplete example (where it is part way through) is the only one that comes up as incomplete.
Using the above data consider the following (noting that no reference is needed to the Outlets table AND that the WHERE clause has been omitted and the GROUP BY according to projectname to show all projects) :-
SELECT
OutletName,
CASE
WHEN (count() * 2 - sum(projStatus)) = 0 THEN 2 ELSE 1
END AS Status,
(count() * 2 - sum(projStatus)) ||' of '||count() AS outstanding
FROM projectparams
GROUP BY projectname
This results in :-
As such there is no need for the Outlet Table the projectparams table, at least according to your example, is sufficient and as such there is no need for a trigger. Whenever an update is made you simply refresh the display using the one table and a query such as the last example.
To demonstrate your scenario step by step consider the following code (based upon the data above i.e. the RA_Pepsi has been added but nothing done) :-
-- First Query
SELECT
OutletName,
CASE
WHEN (count() * 2 - sum(projStatus)) = 0 THEN 2 ELSE 1
END AS Status,
(count() * 2 - sum(projStatus)) ||' of '||count() AS outstanding
FROM projectparams
WHERE projectname = 'RA_Pepsi'AND outletName = 'Tesco'
GROUP BY projectname
;
-- First Update
UPDATE projectparams SET projStatus = 2 WHERE param = 'shelfstrip' AND projectname = 'RA_Pepsi' AND outletName = 'Tesco';
-- 2nd Query
SELECT
OutletName,
CASE
WHEN (count() * 2 - sum(projStatus)) = 0 THEN 2 ELSE 1
END AS Status,
(count() * 2 - sum(projStatus)) ||' of '||count() AS outstanding
FROM projectparams
WHERE projectname = 'RA_Pepsi'AND outletName = 'Tesco'
GROUP BY projectname
;
-- 2nd Update (all completed)
UPDATE projectparams SET projStatus = 2 WHERE param = 'shelfleft' AND projectname = 'RA_Pepsi' AND outletName = 'Tesco';
-- 3rd Query
SELECT
OutletName,
CASE
WHEN (count() * 2 - sum(projStatus)) = 0 THEN 2 ELSE 1
END AS Status,
(count() * 2 - sum(projStatus)) ||' of '||count() AS outstanding
FROM projectparams
WHERE projectname = 'RA_Pepsi'AND outletName = 'Tesco'
GROUP BY projectname
;
The first query shows the project with nothing done as per :-
The 2nd query (after changing the status of the shelfstrip to 2) shows :-
The 3rd query (after changing the status of the shelfleft to 2) shows :-
For Android
The foloowing code demonstrates applying the above on Android and additional uses the recommended convenience methods (they build much of the SQL, off protection against SQL injection and add additional functionality e.g. update returns the number of rows updated) :-
Two methods (the first using the query above, the second updating as per yours but using the update convenience method :-
public String getOutletStatus(String projectname, String outletname) {
String rv = "Ooops nothing found!"; // default if nothing found
String[] columns = new String[]{"outletname",
"CASE " +
"WHEN (count() * 2 - sum(projStatus)) = 0 THEN 2 ELSE 1 " +
"END AS Status", //<<<<<<<<< the column name will be Status
"(count() * 2 - sum(projStatus)) ||' of '||count() AS outstanding" // The column name will be outstanding
};
String whereclause = "projectname=? AND outletName=?";
String[] whereargs = new String[]{projectname,outletname};
String groupby = "projectname"; // not needed
Cursor csr = sqliteHelper.getWritableDatabase().query("projectparams",columns,whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
int statuscode = csr.getInt(csr.getColumnIndex("Status"));
String outstanding = csr.getString(csr.getColumnIndex("outstanding"));
String outlet = csr.getColumnName(csr.getColumnIndex("outletname"));
String statusdescription = "incomplete";
if (statuscode == 2) {
statusdescription = "complete";
}
rv = "The status of project " + projectname + " for outlet " + outlet + " is " + statusdescription + ". With " + outstanding + ".";
}
csr.close();
return rv;
}
public void updateStatus(String projectname, String outletname, String param) {
String whereclause = "projectname=? AND outletname=? AND param=?";
String[] whereargs = new String[]{projectname,outletname,param};
ContentValues cv = new ContentValues();
cv.put("projStatus",2);
int number_of_rows_updated = sqliteHelper.getWritableDatabase().update("projectparams",cv,whereclause,whereargs);
}
They have been tested (using the base data show above) and reflect the final 3 queries with updates between them :-
String status = getOutletStatus("RA_Pepsi","Tesco"); // Before anything
Log.d("RESULT",status);
updateStatus("RA_Pepsi","Tesco","shelfstrip"); //shelfstrip completed
status = getOutletStatus("RA_Pepsi","Tesco");
Log.d("RESULT",status);
updateStatus("RA_Pepsi","Tesco","shelfleft"); //shelfleft completed
status = getOutletStatus("RA_Pepsi","Tesco");
Log.d("RESULT",status);
Result in the Log :-
04-29 12:46:09.615 20471-20471/? D/RESULT: The status of project RA_Pepsi for outlet outletname is incomplete. With 2 of 2.
04-29 12:46:09.621 20471-20471/? D/RESULT: The status of project RA_Pepsi for outlet outletname is incomplete. With 1 of 2.
04-29 12:46:09.625 20471-20471/? D/RESULT: The status of project RA_Pepsi for outlet outletname is complete. With 0 of 2.

SQLite query works on android 4.4, but crashes on android 5.0

The following SQLite query works fine on android 4.4 and below, but it causes an exception: "android.database.sqlite.SQLiteException: ambiguous column name: number (code 1):......" on android 5.0 and later. I checked the SQLite release documents, but did not see any changes that can effect my work. Is there any thing that I missing?
select * from
(
select
'0' as queryid,
CNCT._id,
coalesce(case when length(C.abId)=0 then null else C.abId end,
(
select
addrBkId from numbers as nm,
contacts as cot
where nm.number=coalesce(C.number,S.Number) and nm.contactID = cot._id
order by cot.lastMod desc limit 1)) as addrBkId,
coalesce(
case when length(C.abId)=0 then null else C.abId end,
(
select
addrBkId from numbers as nm,
contacts as cot
where nm.number=coalesce(C.number,S.Number) and nm.contactID = cot._id
order by cot.lastMod desc
limit 1
)
) as uqAddrBkId,
CNCT.displayName,
CNCT.firstName,
CNCT.lastName,
CNCT.favorite,
coalesce(C.location,
(
select
location from calls as css
where css.number = S.Number
)) as location,
0 as numberType,
coalesce(C.number,S.Number) number,
N.txt,A.type,
coalesce(A.callID,A.smsId) actId,
max(A.startEpoch) as maa,
max(A.startTime),
strftime('%w',datetime(A.startEpoch,'unixepoch','localtime'))+0 dayOfWeek,
strftime('%W',datetime(A.startEpoch,'unixepoch','localtime'))+0 weekOfYear,C.duration,
case
when C.callResult='vmail' then 'vmail'||C._id
when C.callType='callin' and C.callResult='missed' then 'missed'
else C.callType end as newCallType,
C.callResult,
C.extension,
C.msgId,
C.audioUrl,
C.name,
C.state,
C.syncParams,
S.smsId,
S.dir,
S.state,
N.noteId,
N.color from activity as A
left outer join calls C on A.callId=C.callId
left outer join sms S on A.smsId=S.smsId
left outer join contacts CNCT on coalesce(case when length(C.abId)=0 then null else C.abId end,
(
select addrBkId from numbers as nm,
contacts as cot
where nm.number=coalesce(C.number,S.Number) and nm.contactID = cot._id
order by cot.updated desc
limit 1)
)=CNCT.addrBkId
left outer join
(
select * from notes as nt
order by nt.lastMod asc
) as N on CNCT.addrBkId=N.addrBkId
where (C.state<>5 or C.state is NULL) and (C.callResult<>'abandoned' or C.callResult is NULL)
group by newCallType,number,weekOfYear,dayOfWeek
order by max(A.startEpoch) asc
)
group by _id
order by maa desc
limit 3
... where nm.number=coalesce(C.number,S.Number) ...
... where nm.number=coalesce(C.number,S.Number) ...
... where css.number = S.Number) ...
... coalesce(C.number,S.Number) ...
... where nm.number=coalesce(C.number,S.Number) ...
... group by newCallType,number,...
^^^^^^
All occurences of number are qualified with a table alias, except the last one. That one indeed is ambiguous.

Fetch data from 3 Tables

I have 3 Tables
1 Customers
-c_id
-c_name
2 Debit_Master
-transaction_id
-c_id
-amount
3 Credit_Master
-transaction_id
-c_id
-amount
Now i want data like this : Customer Name and Total amount(credit amount - debit amount) of each customer .
I want query to fetch data in my listview with two columns 1- Customer Name , 2- Total amount
Try this SQL statement:
SELECT
Customers.c_name as CustomerName,
SUM((CASE
WHEN Credit_Master.amount IS NULL THEN 0
ELSE Credit_Master.amount END -
CASE
WHEN Debit_Master.amount IS NULL THEN 0
ELSE Debit_Master.amount END)) as TotalAmount
FROM Customers
LEFT JOIN Debit_Master on Customers.c_id = Debit_Master.c_id
LEFT JOIN Credit_Master on Customers.c_id = Credit_Master.c_id
GROUP BY Customers.c_id
Try something like this
SELECT Customers.c_name as name , (Credit_Master.amount - Debit_Master.amount) as total FROM Customers JOIN Debit_Master on Customers.c_id=Debit_Master.c_id JOIN Credit_Master on Customers.c_id=Credit_Master.c_id

Issue in join query of multiple tables sqlite

hello friends i have four tables as below
property_master --> "p_id" , "p_name" , "p_address" , "p_city" , "p_state" ,"r_id"
property_unit -->"unit_id" , "p_id" , "unit_name" ,"r_id"
unit_info --> "unit_info_id" ,"unit_id" INTEGER,"p_id" ,"p_bathroom" ,"p_bedroom" ,"p_size" ,"p_rent" ,"p_isrent" ,"u_note" ,"r_id"
tanant_master --> "t_id" , "t_name" ,"t_cell_no" ,"t_phone_no" ,"t_mail" ,"t_deposit" ,"r_id"
property_assign--> "t_assign_id" , "unit_info_id" , "t_id" , "t_start_date" , "t_end_date" , " t_rent_due_day" , "t_lease_alert" , "t_status" ,"r_id"
and my query is as below
Select p_name As "Property",
p_id AS "PID",
(Select Count(unit_id) from property_unit where property_master.p_id=property_unit.p_id )As "UnitCount",
(Select Count(unit_info_id) from unit_info where unit_info.unit_info_id=property_assign.unit_info_id )As "TenantCount"
From property_master ,property_assign Group by property_master.p_id
i need total tenant count propertywise but when i run above query it gives me only first property tenant count for all property any idea how can i solve it?
Try something like this:
select a.PID,
MAX(a.Property) as "Property",
COUNT(a.unit_id) as "UnitCount",
SUM(a.TenantCount) as "TenantCount"
from (
select property_master.p_id as "PID",
MAX(property_master.p_name) as "Property",
property_unit.unit_id,
COUNT(property_assign.t_id) as "TenantCount"
from property_master
JOIN property_unit ON property_master.p_id = property_unit.p_id
JOIN unit_info ON unit_info.unit_id = property_unit.unit_id
JOIN property_assign ON unit_info.unit_info_id = property_assign.unit_info_id
group by property_master.p_id, property_unit.unit_id
) a,
group by a.PID
Note 1 You probably need to use LEFT OUTER JOIN instead of JOIN depends on your data structure (can be property_assign empty or not?)
Note 2. Sorry, I couldn't test it. You should do it yourself.

Categories

Resources