Special Select Statement ( sqlite ) - sqlite

Table: "user"
- Userid - Name -
(every userid is unique)
Table: "money spend"
- Userid - money spend -
(a userid may have several entries with different "money spend")
Now, I need the total sum of the money spend by a user.
To conclude, I need the following view:
- name - sum (money spend) -
Wich statement may give me this result?

You can use an aggregate function and group by:
select u.name, sum(ms.money)
from user u, money_spend ms
where u.userid = ms.userid
group by u.userid
Note that this here assumes that every user has at least 1 row in the money_spend table: http://www.sqlite.org/lang_aggfunc.html
Due to the way that aggregate functions work, you could set up the money_spend table with a 0 value for each user so you don't run into any issues :)

Because you might have users without any entry in table money_spend you need an outer join:
select n.name, sum(ms.money)
from user n
left outer join money_spend ms on (n.userid = ms.userid)
group by n.name
Edit: To be sure this all works I just tried this
create table user(userid, name);
insert into user values (1, 'user1');
insert into user values (2, 'user2');
insert into user values (3, 'user3');
create table moneyspend(userid, amount);
insert into moneyspend values (1,10);
insert into moneyspend values (1,20);
insert into moneyspend values (2,100);
select * from user;
select * from moneyspend;
select u.name, sum(m.amount)
from user u
left outer join moneyspend m on (u.userid = m.userid)
group by u.name;
drop table user;
drop table moneyspend;
The console output is the following (testSQLite is my test DB, testsql.sql is the above)
hols-Mac:div4 hol$ sqlite3 -init testsql.sql testSQLite
-- Loading resources from testsql.sql
1|user1
2|user2
3|user3
1|10
1|20
2|100
user1|30
user2|100
user3|
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>

Related

how to use join with Sqlite Index

I am creating a app with ionic 3. In the app I added a search filter which filter users according to their role. I have 5 tables from which I have to pull the data.In term to do so, I did these steps..
created each table index with the required data.
CREATE INDEX IF NOT EXISTS AccountIndexTable ON Accounts(id,roleId,firstName,lastName,email,accountId);
CREATE INDEX IF NOT EXISTS AddressIndexTable ON Addresses(id,addressTypeId,street,city,state,country,pincode,accountId)
CREATE INDEX IF NOT EXISTS CompanyIndexTable ON Companies(id,name,accountId)
CREATE INDEX IF NOT EXISTS CommunicationIndexTable ON Communications(id,phone,accountId)
CREATE INDEX IF NOT EXISTS OptionalInfoIndexTable ON CustomerOptionalInfos(id,customerType,accountId)
and then i used join to get data. Before that I have questions
1: Do I need to use the indexed table in my join?
the Join query:
SELECT Accounts.accountId AS accountID,
Accounts.roleId AS roleID,
Accounts.email AS email,
Accounts.firstName || " " || Accounts.lastName AS name,
Addresses.street AS street,
Addresses.city AS city,
Addresses.state AS state,
Addresses.country AS country,
Addresses.pincode AS pincode,
Communications.phone AS phone,
Companies.name AS compName,
CustomerOptionalInfos.customerType AS cType
FROM Accounts
LEFT JOIN Addresses ON Addresses.accountId=Accounts.accountId
AND Addresses.addressTypeId=1
LEFT JOIN Communications ON Communications.accountId=Accounts.accountId
LEFT JOIN Companies ON Companies.accountId=Accounts.accountId
LEFT JOIN CustomerOptionalInfos ON CustomerOptionalInfos.accountId=Accounts.accountId
WHERE 1=1
AND Accounts.isDelete!='true'
AND Accounts.firstName!= ''
AND Accounts.roleId = 5
ORDER BY Accounts.firstName ASC
LIMIT ?,?
It still takes +2 seconds to execute. Please suggest me the better way of doing this. I have a large number of data.

Delay delete SQL transactions in an SQR

I am wondering if there is a way to delay Delete transactions in an SQR program? I am having an issue where I am deleting data from a table that has a trigger on it that inserts rows into another (Audit) table and the only key on the table that can be altered is a date/time stamp, but because these transactions are occuring at the exact same time (down to the hundreth of a second) it is causing duplicate insert errors on the sql trigger. I was hoping if there is a way to delay each row to be deleted in SQR that would be a good work-around to this issue. Thanks!
BEGIN-PROCEDURE DELETE-PSROLEUSER-ROLES
SHOW 'BEGINNING DELETE-PSROLEUSER-ROLES'
BEGIN-SQL
DELETE PSRO
FROM PSROLEUSER PSRO
INNER JOIN PS_GH_AD_X_WALK B ON B.OPRID = PSRO.ROLEUSER
INNER JOIN HRDEV01_FOR_BUDGET_MODULE.HRDEV92B.dbo.PS_JOB C ON C.EMPLID = B.GH_AD_EMPLID AND B.GH_AD_EMPLID <> ''
WHERE C.EFFDT =
(SELECT MAX(A_ED.EFFDT) FROM HRDEV01_FOR_BUDGET_MODULE.HRDEV92B.dbo.PS_JOB A_ED
WHERE C.EMPLID = A_ED.EMPLID
AND C.EMPL_RCD = A_ED.EMPL_RCD
AND A_ED.EFFDT <= SUBSTRING(CONVERT(CHAR,GETDATE(),121), 1, 10))
AND C.ACTION = 'TER'
END-SQL
END-PROCEDURE DELETE-PSROLEUSER-ROLES
Please move all of the inner joins to the where clause for the delete. You probably don't intend to delete rows from these inner joined tables, some of which may return multiple rows for an emplid.

Update row with value from next row sqlite

I have the following columns in a SQLite DB.
id,ts,origin,product,bid,ask,nextts
1,2016-10-18 20:20:54.733,SourceA,Dow,1.09812,1.0982,
2,2016-10-18 20:20:55.093,SourceB,Oil,7010.5,7011.5,
3,2016-10-18 20:20:55.149,SourceA,Dow,18159.0,18161.0,
How can I populate the 'next timestamp' column (nextts) with the next timestamp for the same product (ts), from the same source? I've been trying the following, but I can't seem to put a subquery in an UPDATE statement.
UPDATE TEST a SET nextts = (select ts
from TEST b
where b.id> a.id and a.origin = b.origin and a.product = b.product
order by id asc limit 1);
If I call this, I can display it, but I haven't found a way of updating the value yet.
select a.*,
(select ts
from TEST b
where b.id> a.id and a.origin = b.origin and a.product = b.product
order by id asc limit 1) as nextts
from TEST a
order by origin, a.id;
The problem is that you're using table alias for table in UPDATE statement, which is not allowed. You can skip alias from there and use unaliased (but table-name prefixed) reference to its columns (while keeping aliased references for the SELECT), like this:
UPDATE TEST
SET nextts = (
SELECT b.ts
FROM TEST b
WHERE b.id > TEST.id AND
TEST.origin = b.origin AND
TEST.product = b.product
ORDER BY b.id ASC
LIMIT 1
);
Prefixing unaliased column references with the table name is necessary for SQLite to identify that you're referencing to unaliased table. Otherwise the id column whould be understood as the id from the closest[*] possible data source, in which case it's the aliased table (as b alias), while we're interested in the unaliased table, therefore we need to explicitly tell SQLite that.
[*] Closest data source is the one listed in the same query, or parent query, or parent's parent query, etc. SQLite is looking for the first data source (going from inner part to the outside) in the query hierarchy that defines this column.

Can multitable Insert statement combine columns from view and columns from another view?

I'm planning to do SQL expert examination.
I have doubts that answer D is correct:
Evaluate the following command:
CREATE TABLE employees
( employee_id NUMBER(2) PRIMARY KEY
, last_name VARCHAR2(25) NOT NULL
, department_id NUMBER(2)NOT NULL
, job_id VARCHAR2(8)
, salary NUMBER(10,2));
You issue
the following command to create a view that displays the IDs and last
names of the sales staff in the organization:
CREATE OR REPLACE VIEW sales_staff_vu AS
SELECT employee_id, last_name,job_id
FROM employees
WHERE job_id LIKE 'SA_%'
WITH CHECK OPTION;
Which two statements are true regarding the above view? (Choose two.)
A. It allows you to insert rows into the EMPLOYEES table .
B. It allows you to delete details of the existing sales staff from
the EMPLOYEES table.
C. It allows you to update job IDs of the existing sales staff to any
other job ID in the EMPLOYEES table.
D. It allows you to insert IDs, last names, and job IDs of the sales
staff from the view if it is used in multitable INSERT statements.
Source
A is FALSE as the view doesn't allow inserting into the department_id column which is mandatory.
B is TRUE, although it would be more accurate to say that the view only allows deletions of employees where the job_id matches the predicate LIKE 'SA_%'.
C is FALSE, as the WITH CHECK OPTION means that you can't change the job_id if the new job_id doesn't match the view's predicate.
D is FALSE: a multitable insert statement can't just insert some columns into the view and the remaining columns into the employees table. Even if you join the view to the table, the insert must still insert into the base table, not into the view:
insert into
(select e.employee_id, e.last_name, e.department_id, e.job_id
from sales_staff_vu v
join employees e
on v.employee_id = e.employee_id)
values
(1, 'KEMP', 2, 'SA_X');
I suspect this is a test of your ability to verify and ignore wrong information on the internet - i.e. 99% of sites say D is true!
Now, my answer can be easily disproved by crafting a multitable insert statement that successfully inserts via the view.
According to my knowledge answer D is wrong.Reasons are
1.If A is wrong, definitely D is wrong.because department_id column is mandatory field on the table, but it is not mentioned in view.so we can't insert a row using this view.
2.In Answer D,multitable INSERT statements are INSERT ALL, INSERT FIRST,etc.
to check this Answer,i have tried these steps
CREATE TABLE employees123
( employee_id NUMBER(2) PRIMARY KEY
, last_name VARCHAR2(25) NOT NULL
, department_id NUMBER(2)NOT NULL
, job_id VARCHAR2(8)
, salary NUMBER(10,2));
CREATE OR REPLACE VIEW sales_staff_vu123 AS
SELECT employee_id, last_name,job_id,department_id
FROM employees123
WHERE job_id LIKE 'SA_%'
WITH CHECK OPTION;
--department_id is added to view
--here i am trying to insert my employees table rows to employees123 table
INSERT ALL
INTO sales_staff_vu123 --using View
SELECT employee_id, last_name,job_id,department_id
FROM employees;
Error at Command Line:153 Column:15
Error report:
SQL Error: ORA-01702: a view is not appropriate here
01702. 00000 - "a view is not appropriate here"
*Cause:
*Action:
So my decision is we cant use views with multitable insert statements.

Linq to Entities: Left join to get items NOT found in the join

I've got two un-related (no FK's defined) tables. The first table contains some tasks for which a user may not have access. I need to find all those tasks - in this case, the joined table would contain nulls. How do I get them?
Here's the setup:
TimeData table
- userID
- taskID
- hours
ApprovedTasks table (the one that should contain nulls)
- taskID
- userID
The SQL query would look like this:
select * from TimeData td
left join ApprovedTasks at
on at.taskID = td.taskID and at.userID = td.userID
where at.taskID is null
Any way to pull that off using a LINQ to Entity query?
TIA
Check out... Disjoint Union in LINQ
This should work...
var approvedTaks = from at in ApprovedTasks.Except(
from at2 in ApprovedTasks
where at2.userID == userId and at2.taskID==taskId
select at2)
where at.userID == userId and at.taskID==taskId
select at;
but sorry don't have the database handy to test it.

Resources