How to get distinct and lastest record with inner join query - sql

I have two table named: customers and bill. customer and bill have one to many relation.
Customer table contains record of customer mobileNo,bikeNo etc
Bill table contain record of customer bill with bikeNo(foreign key),billdate etc.
I have query for that:
SELECT customer.mobileNo, bill.iDate AS Expr1
FROM (customer INNER JOIN
bill ON customer.bikeNo = bill.bikeNo)
ORDER BY bill.iDate;
Now How i get distinct and latest billdate record and mobileNo with this query?

Use GROUP BY and MAX():
SELECT customer.mobileNo, MAX(bill.iDate) AS iDate
FROM (customer INNER JOIN
bill ON customer.bikeNo = bill.bikeNo)
GROUP BY customer.mobileNo
ORDER BY iDate

Related

Selecting students who have not made any payment in a given period (term)

I have two tables: students and payments.
students has the columns:
first_name
last_name
student_id
class_name
payments table has the columns:
full_name
student_id
term
session
amount_paid
class_fee
The details of every student is in the students table, but only those who have made either full or part payment enters the payments table. I have written a query to select those who have paid.
The question now is how to write a query that will select those in a particular class that have made no payment at all in a given period (term).
You are probably using a JOIN to select those who have paid. That will work because there are matching rows in both tables. To find those who have not paid, you can use a LEFT JOIN. It will give you NULL if rows do not match.
SELECT students.*
FROM students
LEFT JOIN payments ON students.student_id = payments.student_id
AND term = 'whatever'
WHERE amount_paid IS NULL
(Note: the term = 'whatever' needs to be in the ON clause, not the WHERE)
You can also do this using a subquery and the NOT EXISTS clause. NOT EXISTS will return true if the subquery returns zero rows.
SELECT *
FROM students
WHERE NOT EXISTS(
SELECT amount_paid
FROM payments
WHERE students.student_id = payments.student_id
AND term = 'whatever'
)

Two group by tables stich another table

I have 3 tables I need to put together.
The first table is my main transaction table where I need to get distinct transaction id numbers and company id. It has all the important keys. The transaction ids are not unique.
The second table has item info which is linked to transaction id numbers which are not unique and I need to pull items.
The third table has company info which has company id.
Now I've sold some of these with the first one through a group by id. The second through a subquery which creates unique ids and joins onto the first one.
The issue I'm having is the third one by company. I cannot seem to create a query that works in the above combinations. Any ideas?
As suggested here is my code. It works but that's because for the company I used count which doesn't give the correct number. How else can I get the company number to come out correct?
SELECT
dep.ItemIDAPK,
dep.TotalOne,
dep.company,
company.vendname,
appd.ItemIDAPK,
appd.ItemName
FROM (
SELECT
csi.ItemIDAPK,
sum(f.TotalOne) as TotalOne,
count(f.DimCurrentcompanyID) company
FROM dbo.ReportOne F with (nolock)
INNER JOIN dbo.DSaleItem csi with (nolock)
on f.DSaleItemID = csi.DSaleItemID
INNER JOIN dbo.DimCurrentcompany cv
ON f.DimCurrentcompanyID = cv.DimCurrentcompanyID
INNER JOIN dbo.DimDate dat
on f.DimDateID = dat.DimDateID
where (
dat.date >='2013-01-29 00:00:00.000'
and dat.date <= '2013-01-30 00:00:00.000'
)
GROUP BY csi.ItemIDAPK
) as dep
INNER JOIN (
SELECT
vend.DimCurrentcompanyID,
vend.Name vendname
FROM dbo.DimCurrentcompany vend
) As company
on dep.company = company.DimCurrentcompanyID
INNER JOIN (
SELECT
c2.ItemIDAPK,
ItemName
FROM (
SELECT DISTINCT ItemIDAPK
FROM dbo.dimitem AS C
) AS c1
JOIN dbo.dimitem AS c2 ON c1.ItemIDAPK = c2.ItemIDAPK
) as appd
ON dep.ItemIDAPK = appd.ItemIDAPK
For further information my output is the following example, I know the code executes and the companyid is incorrect as I just put it with a (count) in their to make the above code execute:
Current Results:
Item Number TLS CompanyID Company Name Item Number Item Name
111111 300 303 Johnson Corp 29323 Soap
Proposed Results:
Item Number TLS CompanyID Company Name Item Number Item Name
111111 300 29 Johnson Corp 29323 Soap

Joining and aggregating data from multiple tables

In customer table there is a SupportID which is the WorkerId in the worker Table, each WorkerId shows which will handle that customer.
Working Name | No. of accounts | total revenue
----------------------------------------------
John McCoy 20 10,000
Worker table contains - Firstname, Lastname, EmployeeId
Receipt table contains - receipt Id, CustomerId,
ReceiptLine Table contains - receiptlineId, receipt Id, Unitprice, quantity
At the moment I have this code / idea
SELECT FirstName, LastName
FROM Employee A, Invoice B
WHERE A.EmployeeId = B.CustomerId
In this question, you have not mention dependency among worker and receipt table. However, let the dependency column is workerId on table receipt. Now try this, hope you will get your desired result.
select a.firstName, sum(count(b.customerId)) as no_accounts, sum(c.unitPrice *c.quantity) as total_revenue
from (( worker a join receipt b on a.workerId = b.SupportId)
join receiptLine c on b.receiptId = c.receiptId) group by a.firstName order by a.firstName;
use GROUP BY to resolve your problem

Query to select related data from two tables in which one table has no related fields in third table

I have three tables in my Oracle db:
Peoples:
IdPerson PK
Name
Surname
Earnings:
IdEarning PK
IdPerson
EarningValue
Awards:
IdAward PK
IdPerson FK
AwardDescription
So one person can have many earnings, one earning or can have no any earnings. Also one person can have many awards, one award, or no any award.
I have to select Surname and AwardDescription but only for people who have any earnings, because it is possible to have some award but, also don't have any earning!
My problem is to make a correct group by statement. I use query posted below and I am selecting surname of person with a description of award, but it is duplicating for each row in Earnings for this person.
SELECT AwardDescription, Surname
FROM Awards
INNER JOIN People ON People.IdPerson= Awards.IdPerson
INNER JOIN Earnings ON Earnings .IdPerson= People.IdPerson;
How to group it and avoid duplicating rows for each earning of person?
One person can be in many rows, but with different awards.
You could add DISTINCT to your query:
SELECT DISTINCT AwardDescription, Surname
FROM Awards
INNER JOIN People ON People.IdPerson= Awards.IdPerson
INNER JOIN Earnings ON Earnings .IdPerson= People.IdPerson;
Or another option is to use EXISTS:
SELECT AwardDescription, Surname
FROM Awards
INNER JOIN People P ON P.IdPerson= Awards.IdPerson
WHERE EXISTS (
SELECT 1
FROM Earnings E
WHERE P.IdPerson = E.IdPerson);
Do a left outer join among the tables like
SELECT p.Surname, a.AwardDescription, e.EarningValue
FROM People p
LEFT JOIN Awards a ON p.IdPerson= a.IdPerson
LEFT JOIN Earnings e ON e.IdPerson= p.IdPerson
WHERE a.AwardDescription IS NOT NULL
OR e.EarningValue IS NOT NULL;

how to use inner join queries for four tables

I have four tables in my database(notes, expense, category and items).
items table will have so many items on the particular category id
items table have fields
id(primary key), item name(text), unit(text), category id(foreign key)
category table will have just two fields
category table have fields
id(primary key), cat_id(integer), category name(text).
notes table is used to have a record for each shopping note.
notes table have fields
note_id(primary key), date(DATE), total cost(integer).
expense table is used to store the items purchased and its corresponding quantity and price under the particular shopping note using note id as the foreign key
expense table has fields
id(primary key), note_id(foreign key), quantity(integer), price(integer), item_name(text)
When I input the from date,to date and a particular category i need the items under that category that was purchaed between the from and to date.
i need a query that will give output as:
ITEM NAME TOTALQTY TOTALPRICE
carrot 5kg 500
can anyone help me with a solution??
Try this
select A.name, sum(C.unit), A.unit, sum(C.price)
from items as A
INNER JOIN categories as B ON A.category=B._id
INNER JOIN expenses as C ON A.name=C.item_name
INNER JOIN notes as D ON C.Note_id=D._id
where
D.date1 between '2012-01-01' and '2012-03-31' and B.name='Vegetables'
group by
A.name, A.unit