Updating records with addition using sub queries in SQLite - sqlite

I am attemping to update a record in table StockCatalog called Product Quantity by adding Product Quantity together with a record called DeliveryQuantity in table DeliveryContent whilst inner joining two records, StockCatalog.StockID = DeliveryContent.StockID inner joining DeliveryContent.DeliveryID = Deliveries.DeliveryID. So far I have this:
UPDATE StockCatalog
SET ProductQuantity = (SELECT StockCatalog.ProductQuantity FROM StockCatalog INNER JOIN DeliveryContent on StockCatalog.StockID = DeliveryContent.StockID WHERE StockCatalog.ProductQuantity + DeliveryContent.DeliveryQuantity)
WHERE (SELECT DeliveryContent.DeliveryID FROM DeliveryContent INNER JOIN Deliveries on DeliveryContent.DeliveryID = Deliveries.DeliveryID)
However it appears that this updates all ProductQuantity records in StockCatalog with one record of DeliveryQuantity in DeliveryContent. Sorry If this is confusing.

Seems to be some confusion about WHERE going on. I GUESS this is what you want:
UPDATE StockCatalog sc SET ProductQuantity = ProductQuantity +
( SELECT DeliveryQuantity FROM DeliveryContent WHERE StockID=sc.StockID )
WHERE StockID in (select StockID from DeliveryContent);
If more than one DeliveryContent can exist for each StockID, maybe DeliveryQuantity should be replaced by SUM(DeliveryQuantity).

Related

How to use left outer join in my sql query?

Here is my query:
ALTER PROCEDURE sp_logdetails
(
#bookid INT
)
AS
BEGIN
SELECT *
FROM book_lending
LEFT OUTER JOIN student ON student.id = book_lending.id
WHERE bookid = #bookid
END
When i execute above query, it shows only book_lending data, not the student data. Here is my screenshot
And it is my student table data screenshot:
May i know, how to get student data in which particular bookid. I used to set foreign key for book_lending id to student id.
Can anyone guide me to fix this?
Thanks,
Select the specific columns from joined table in your select list. Here bl and s is table alias for better redability. You need to select the columns you want and include them to your select list. below query will select all columns from both tables.
SELECT bl.*, s.*
FROM book_lending bl
LEFT OUTER JOIN student s ON s.id = bl.id
AND bl.bookid = #bookid
You got the fields mixed up in the join:
LEFT OUTER JOIN student ON student.id = book_lending.id
You try to match a student to book lending by ID of both - which is wrong.
Change the code to this and you will start getting results back:
SELECT *
FROM book_lending
LEFT OUTER JOIN student ON student.id = book_lending.studentid
WHERE bookid = #bookid

Sequence in sql operation?

I am passing datatable as input parameter to stored procedure. Datatable contains id, Name,Lname,Mobileno,EmpId.
Employee table contains [Name],[Lname],[mobno],[Did] as columns.
When user is logged in, his Id come as DId. There are more than 1000 records. Instead of passing that id to datatable, I have created
separete parameter to sp. I want to add records to Employee table, which are not already exist. If combination of mobileno and Did already exists, then
don't insert into Employee table, else insert. Datatable may contain records, which can be duplicate. So I don't want to include that record. I want select only
distinct records and add them to table. I am intrested in mobile no. If there are 10 record having same moble no, I am fetching record, which comes first.
Following code is right or wrong. According to my knowledge, first from clause, then inner join, then where, then select execute. Record get fetched from datatable,
then inner join happens generate result, from that result not from datatable it will check record. So it will give me proper output.
Create Procedure Proc_InsertEmpDetails
#tblEmp EmpType READONLY,
#DId int
as
begin
INSERT INTO Employee
([Name],[Lname],[mobno],[Did])
SELECT [Name],[Lname],[mobno] #DId
FROM #tblEmp A
Inner join (
select min(Id) as minID, mobno from #tblEmp group by mobno
) MinIDTbl
on MinIDTbl.minID = A.ExcelId
WHERE NOT EXISTS (SELECT 1
FROM Employee B
WHERE B.[mobno] = A.[mobno]
AND B.[Did] = #DId )
end
or does I need to change like this
INSERT INTO Employee
([Name],[Lname],[mobno],[Did])
SELECT C.[Name],C.[Lname],C.[mobno], C.D_Id
from
(SELECT [Name],[Lname],[mobno] #DId as D_Id
FROM #tblEmp A
Inner join (
select min(Id) as minID, mobno from #tblEmp group by mobno
) MinIDTbl
on MinIDTbl.minID = A.ExcelId
)C
WHERE NOT EXISTS (SELECT 1
FROM Employee B
WHERE B.[mobno] = C.[mobno]
AND B.[Did] = #DId )

Sqlite double left outer join with count

I have the following DB structure:
tbl_record(_id,_id_user,...)
tbl_photo(_id,_id_record,...)
tbl_note(_id,_id_record,...)
When listing the records of a specific user while counting the number of photos a record has, I use the following query, which works fine:
SELECT tbl_record._id, COUNT(tbl_photo._id_record) AS photo_count FROM tbl_record
LEFT OUTER JOIN tbl_photo ON tbl_record._id=tbl_photo._id_record
WHERE tbl_record._id_user=? GROUP BY tbl_record._id;
Now, I'd like to do the same as above, but also count the number of notes a record has:
SELECT tbl_record._id, COUNT(tbl_photo._id_record) AS photo_count, COUNT(tbl_note._id_record) AS note_count FROM tbl_record
LEFT OUTER JOIN tbl_photo ON tbl_record._id=tbl_photo._id_record
LEFT OUTER JOIN tbl_note ON tbl_record._id=tbl_note._id_record
WHERE tbl_record._id_user=? GROUP BY tbl_record._id;
The count of the 2nd query does not work properly when a record has >0 photos & >0 notes, e.g. 3 photos & 5 photos which results in a count of 15 (3*5) for each.
Any idea how to make the 2nd query return the proper counts?
Thanks!!
You might be able to filter out duplicates by using COUNT(DISTINCT some_id), but this would be inefficient.
Better use correlated subqueries:
SELECT _id,
(SELECT COUNT(*)
FROM tbl_photo
WHERE _id_record = tbl_record._id
) AS photo_count,
(SELECT COUNT(*)
FROM tbl_note
WHERE _id_record = tbl_record._id
) AS note_count
FROM tbl_record
WHERE _id_user = ?

SQLite outer join column filtering

As a training exercise I'm working on a fictional SQLite database resembling League of Legends, and I need to perform a left outer join to get a table of all players and if they have skins that are not called 'Classic', return those too.
I currently have this query:
SELECT * FROM players
LEFT OUTER JOIN (SELECT * FROM playerchampions WHERE NOT championskin = 'Classic')
ON name = playername
Which returns what I am looking for, but also a lot of columns I don't want (player experience, player IP, player RP, playername in the playerchampions table. The code for the two tables is as following:
CREATE TABLE players (
name TEXT PRIMARY KEY,
experience INTEGER,
currencyip INTEGER,
currencyrp INTEGER
);
CREATE TABLE playerchampions (
playername TEXT REFERENCES players ( name ) ON UPDATE CASCADE,
championname TEXT REFERENCES champions ( name ) ON UPDATE CASCADE,
championskin TEXT REFERENCES skins ( skinname ) ON UPDATE CASCADE,
PRIMARY KEY ( playername, championname, championskin )
);
As I said, the query executes, but I can't use SELECT players.name, playerchampions.championname, playerchampions.championskin as the playerchampions columns are not given their proper table name when returned.
How do I fix this?
Try using aliases:
SELECT p.name, c.championskin FROM players p LEFT OUTER JOIN (SELECT pc.playername playername, pc.championskin championskin FROM playerchampions pc WHERE NOT pc.championskin = 'Classic') c ON p.name = c.playername;
Not sure if its exactly what you need, but it will get you closer...
SELECT * FROM players p LEFT OUTER JOIN playerchampions pc ON (p.name = pc.playername) WHERE NOT pc.championskin = 'Classic'

How to filter old entries with unique id out of SQL query

I have a table and a relation
I have maybe 10 Submissions, but when I query the database I only want to get those with a Unique CaseId and the one to return should be the one with the newest Date. Is it possible (And adviceable) to do this in a single query or should I do the filtering in my asp.nets code behind where I fetch the data?
Edit: New images
Here you can see that I show many items with the same case id, I only want to show the latest one (Based on date)
This is my current sql query
SELECT Submission.Id, Date, center.Name as CenterName, center.Id as CenterId, subject.Name as SubjectName, subject.Id as SubjectId, EmployeeName, Reason, Description, Explanation, Done, ChiefLevel, Action, CaseId
FROM Submission, subject, center
WHERE center.Id=CenterId AND subject.Id=SubjectId
ORDER BY Date DESC;
SELECT caseid
FROM
(
SELECT caseid, max(date) AS max_date
FROM submission
GROUP BY caseid
) a
JOIN subject t ON a.subjectid=t.id
My QUERY ended up being this
SELECT s.Id, s.Date, c.Name as CenterName, c.Id as CenterId, su.Name as SubjectName, su.Id as SubjectId, s.EmployeeName, s.Reason, s.Description, s.Explanation, s.Done, s.ChiefLevel, s.Action, s.CaseId
FROM submission as s
INNER JOIN
(
SELECT CaseId, MAX(Date) AS MaxDateTime
FROM submission
GROUP BY CaseId
) as groupeds
ON s.CaseId = groupeds.CaseId
AND s.`Date` = groupeds.MaxDateTime
INNER JOIN
(
SELECT Id, Name
FROM subject
) as su
ON su.Id=SubjectId
INNER JOIN
(
SELECT Id, Name
FROM center
) as c
ON c.Id=CenterId;

Resources