Inner Join 2 Column Return - self-join

I need to build a query that I believe needs different types of joins, but I am not sure how to write it.
I have a customers table and an orders table. I need a query that will return 2 columns displaying the following:
1- list of all customer_id that have never had an order
2- list of all customer_ID that have 1 or more record in the orders table
I have this left join query but i feel like its missing something that indicates the customers column should not have a value on the orders table?
SELECT Customers.userid, Orders.userid
FROM Customers
LEFT JOIN ORDERS
ON Customers.userid=orders.USER_ID

Related

include summation of value from one table when joining tables for sqlite

I have two tables, one with Tours and the other with Joiners.
For the Tours table someone proposes a date, route, number of people and other factors for the tour.
For the Joiners table, groups click checkboxes in the Tours table indicating which Tours they would like to join.
I would like to show a column in the Tours table how many people are interested in that tour.
For the Joiners table I have:
$sql = "SELECT tourid,SUM(ppl) FROM joiners GROUP BY tourid";
which correctly calculates the total number of people interested in joining each tour, where ppl is the number of people in each group.
For the Tours (requests) table I tried:
$sql = "SELECT requests.id,requests.startdate,requests.wherestart,requests.duration,requests.ppl FROM requests
LEFT JOIN joiners
ON requests.id = joiners.tourid
ORDER BY startdate";
but can't seem to figure out how to draw on the sum(ppl) amount from the Joiners table to insert it in the relevant column of the relevant tour/id of the Tour table.
You can join your 1st query to the table requests like this:
SELECT r.id, r.startdate, r.wherestart, r.duration, r.ppl,
r.ppl + SUM(j.ppl) AS total
FROM requests AS r LEFT JOIN joiners AS j
ON r.id = j.tourid
GROUP BY r.id, r.startdate, r.wherestart, r.duration, r.ppl
ORDER BY r.startdate
In your question you say that the column ppl is in the table joiners, but your 2nd query contains a column requests.ppl which (I assume) you want to sum.
I included in the SELECT list a column r.ppl, but if this does not exist then delete it also from the GROUP BY clause.
It is a good practice to use aliases for the tables and qualify all the column names with these table aliases.

Using querys to get information from different tables

I am learning SQLite and I'm using this database to learn how to correctly use querys but I'm struggling specially when I have to use data from multiple tables to get some information.
For example, with the given database, is there a way to get the first name, last name and the name of songs that every customer has bought?
All you have to do is a simple SQL SELECT query. When you say you're having trouble getting it from multiple tables, I'm not sure if you're trying to get the data from all of the tables in one single query, as that is not necessary. You just need to have multiple instances of the SELECT query, just for different tables (and different column names).
SELECT firstName, lastName, songName FROM table_name
You have to study about JOINS:
select
c.FirstName,
c.LastName,
t.Name
from invoice_items ii
inner join tracks t on t.trackid = ii.trackid
inner join invoices i on i.invoiceid = ii.invoiceid
inner join customers c on c.customerid = i.customerid
In this query there are 4 tables involved and the diagram in the link you posted, shows exactly their relationships.
So you start from the table invoice_items where you find the bought songs and join the other 3 tables by providing the columns on which the join will be set.
One more useful thing to remember: aliases for tables (like c for customers) and if needed for columns also.
You need to use joins to get data from multiple tables. In this case I'd recommend you using inner joins.
In case your are not familiar with joins, this is a very good article that explains the different types of joins supported in SQLite.
SQLite INNER JOINS return all rows from multiple tables where the join
condition is met.
This query will return the first and last name of customers, and the tracks they purchased.
select customers.FirstName,
customers.LastName,
tracks.name as PurchasedTracks from invoice_items
inner join invoices on invoices.InvoiceId = invoice_items.InvoiceId
inner join customers on invoices.CustomerId = customers.CustomerId
inner join tracks on invoice_items.TrackId = tracks.TrackId
order by customers.LastName

select query with sum value from another table

I'm working with SQLite and have 3 tables, project, invoice and order. I have a select statement based on the project table which picks off the fields stored in this table, however I would also like the sum value of invoices for a particular project and the sum value of orders for a particular project. I know how to get all the values individually, however I haven't figured out how to get the Sum value of orders/invoices into the project data row. Is it a nested select I need to search for, or another concept?
Select based on project table
SELECT project.projectID, project.project_title, project.end_date, project.project_manager, project_status.project_status
FROM project
LEFT JOIN project_status
ON project.project_statusID=project_status.project_statusID
WHERE project.project_statusID BETWEEN 1 AND 12
Select based on invoice table where x would be the project id from the first select
SELECT sum(invoice_net)
FROM invoice
WHERE projectID= x
Select based on order table where x would be the project id from the first select
SELECT sum(total_order)
FROM order
WHERE projectID = x
You didn't provide sample data or even enough of your DB schema for an answer to provide the exact SQL you need.
You don't describe the invoice or order tables. I have to assume they contain a ProjectID attribute.
You could use a subselect:
http://www.techrepublic.com/article/use-sql-subselects-to-consolidate-queries/1045787/
https://msdn.microsoft.com/en-us/library/ff487138.aspx
You're select might look something like (untested):
SELECT
project.projectID,
project.project_title,
project.end_date,
project.project_manager,
project_status.project_status,
(SELECT sum(invoice.invoice_net) FROM invoice WHERE invoice.projectID = project.projectID),
(SELECT sum(order.total_order) FROM order WHERE order.projectID = project.projectID)
FROM project
LEFT JOIN project_status
ON project.project_statusID=project_status.project_statusID
WHERE project.project_statusID BETWEEN 1 AND 12
Or a Join with a Group By. See:
SQL JOIN, GROUP BY on three tables to get totals
You'll have to group by all the non-aggregated (in general this will be all the fields you select from your project table), then apply an aggregate function (sum) to your detail attributes (invoice_net and total_order).
Like this (untested):
SELECT
project.projectID,
project.project_title,
project.end_date,
project.project_manager,
project_status.project_status,
sum(invoice.invoice_net),
sum(order.total_order)
FROM project
LEFT JOIN project_status
ON project.project_statusID=project_status.project_statusID
LEFT JOIN invoice
ON project.projectID = invoice.projectID
LEFT JOIN order
ON project.projectID = order.projectID
WHERE project.project_statusID BETWEEN 1 AND 12
GROUP BY project.projectID, project.project_title, project.end_date,
project.project_manager, project_status.project_status
Which to choose? Performance should be comparable, but it's possible a weakness in the query optimizer could lead to one being favored over the other. Test performance if this is important.
For a one-off, I'd probably use the subselect, if a view of the joined tables didn't already exist. But in practice a view does or should exist, in which case using that (or creating the view, if needed), with GROUP BY, is pretty natural.
So the real answer becomes (untested):
CREATE VIEW project_order_invoice AS
SELECT
project.projectID,
project.project_title,
project.end_date,
project.project_manager,
project_status.project_status,
invoice.invoice_net,
order.total_order
FROM project
LEFT JOIN project_status
ON project.project_statusID=project_status.project_statusID
LEFT JOIN invoice
ON project.projectID = invoice.projectID
LEFT JOIN order
ON project.projectID = order.projectID
SELECT
projectID,
project_title,
end_date,
project_manager,
project_status,
sum(invoice_net),
sum(total_order)
FROM project_order_invoice
WHERE project_statusID BETWEEN 1 AND 12
GROUP BY projectID, project_title, end_date,
project_manager, project_status
For the view, you'll probably want to include all the attributes from all the tables, except only 1 copy of the ID attributes.

Return a column once time

I execute a query in my DB:
SELECT table1.*, tabl2.* FROM table1 JOIN table2 USING(id);
In these 2 tables i have a common column "id". What I have to ask, in order to get the column 'id' once time in the results and not twice?
I thought one solution is to write down in the query which columns I want. But If I want to avoid this (as there are many) ?
Will it work for you to name specific columns you need from both tables? something like:
SELECT table1.id, table2.other_column1, table2.other_column2 FROM table1 JOIN table2 USING(id);
You are selecting all fields from both tables by using (*)

How to fetch data from two different tables?

Good noon to every one
my query is that i have one table name Purchase&Sales and two different field
Purchase
Sales
the data which will be in Purchase text box will be fetch from Total purchase table
and the data will be in sales table will be fetch from Total Sales Table
means the both Value will come from different table to one table
So please Give me a syntax or some idea
Hoping for your Great and positive response
select sum(Purchase) Result from PurchaseTable
union all
select sum(Sales) Result from SalesTable
Using JOIN or try with ForeignKey concept if any.
SELECT
S.Total, -- selecting from one table
P.Total -- selecting from another table
FROM
Sales S
INNER JOIN -- inner join if you can or similar
Purchase P
ON
S.PurchaseId = P.ID
see here for more info http://www.techrepublic.com/article/sql-basics-query-multiple-tables/

Resources