Combine 4 tables in Postgres - database

I have four tables and I need to extract individual cost for every owner. The price of the procedure is in proceduredetails table and the name of the owner is from owners table. The two tables do not have the same column. I have to reference the pets table and the procedurehistory table to link them.
This is my current query
select owners.name ||' '|| owners.surname AS Owner, sum(proceduredetails.price) as price
from owners, proceduredetails
join pets p on owners.ownerid = p.ownerid
inner join procedurehistory p2 on p.petid = p2.petid
group by owners.ownerid;
I got an error
ERROR: invalid reference to FROM-clause entry for table "owners" Hint:
There is an entry for table "owners", but it cannot be referenced from
this part of the query.

Apply inner join instead of cross join and proper relationship. As ownerid is used in group by clause so MAX() is used for owner name because ownerid is unique. Otherwise use ow.name ||' '|| ow.surname in group by clause instead of ownerid.
-- PostgreSQL
SELECT MAX(ow.name ||' '|| ow.surname) AS Owner
, SUM(pd.price) as price
FROM owners ow
INNER JOIN pets p
ON ow.ownerid = p.ownerid
INNER JOIN procedurehistory p2
ON p.petid = p2.petid
INNER JOIN proceduredetails pd
ON pd.proceduretype = p2.proceduretype
GROUP BY ow.ownerid;

Related

Create stored procedure and write a query for joining multi table based on columns in SQL Server

I am beginner to SQL, this is my first exercise to create a stored procedure​ in SQL. I need to get all the rows of all the persons with columns FirstName, MiddleName, LastName, email address, phone number and phonenumber type.
I have to join (required to use join) these 4 tables Person.person, person.personphone, person.phonenumbertype, person.emailaddress and retrieve the columns mentioned above.
The data I am using is the AdventureWorks 2016 SQL Server sample database, which has around 20k rows.
I tried inner joining on two tables to start with and the execution seems never ending.
select FirstName as firstname
from Person.Person
inner join person.EmailAddress on Person.Person.BusinessEntityID = Person.EmailAddress.BusinessEntityID
Thanks allmhuran and marc_s for the corrections.
Advice any link or suggestions on how I can get solution to this query.
You need something like this:
-- select the columns you want
SELECT
p.FirstName, p.MiddleName, p.LastName,
pe.EmailAddress, pp.PhoneNumber, pnt.Name AS PhoneNumberType
FROM
-- this is your "base" table - where most of the info exists
Person.Person p
INNER JOIN
-- join to the e-mail table - based on "BusinessEntityID", to get e-mail address
Person.EmailAddress pe ON pe.BusinessEntityID = p.BusinessEntityID
INNER JOIN
-- join to the person phone table - based again on "BusinessEntityID", to get phone number
Person.PersonPhone pp ON pp.BusinessEntityID = p.BusinessEntityID
INNER JOIN
-- join the PersonPhone table to the PhoneNumberType table, to get the type of phone
Person.PhoneNumberType pnt ON pnt.PhoneNumberTypeID = pp.PhoneNumberTypeID
You should always use proper / meaningful aliases for your tables - this makes your list of columns being selected, and your JOIN conditions, just so much more readable!

How to find different names of cities via several tables

I have five tables that contain artificial data about bank details.
My intention is to select only transactions that took place in a different city than that of the customer they belong to.
In order to do this, I wrote this query:
SELECT c.Cityid,c.FirstName,c.LastName,ci.Name
FROM dbo.Customer c
INNER JOIN dbo.City ci ON ci.ID=c.Cityid
INNER JOIN dbo.Account acc ON acc.CustomerId=c.Id
INNER JOIN dbo.AccountDetails accde ON accde.AccountId=acc.Id
INNER JOIN dbo.Location lo ON lo.LocationTypeId=accde.LocationId
WHERE c.Cityid <>lo.CityId
But unfortunately I have results that are not good and my code listed data which is identical like city of customer, not city of transaction. Probably I have some mistake with WHERE expression.
So can anybody help me how to fix this problem ?
Also here in attachment there is diagram of tables in database.
Additionally here I put screen-shot from Customer table.In last column here there is CityId marked with yellow color.
Each of this customer have some transaction in City which is diffrent than their cities.For example for customer with Id 1 I need to have all other cities that this customer have transaction.In order to achive this I connect customer table with account details and account table.And the end I need to have city for each cusmtomer which is diffrent than their city. Also here I will put Location table
If you want to display city of transaction too, join the city table again:
SELECT
c.FirstName,
c.LastName,
ci.Name as customer_city,
tci.Name as transaction_city
FROM dbo.Customer c
JOIN dbo.City ci ON ci.ID=c.Cityid
JOIN dbo.Account acc ON acc.CustomerId=c.Id
JOIN dbo.AccountDetails accde ON accde.AccountId=acc.Id
JOIN dbo.Location lo ON lo.LocationTypeId=accde.LocationId
JOIN dbo.City tci ON tci.ID=lo.Cityid -- Added join to city from location
WHERE c.Cityid <>lo.CityId
I added another join to City from Location.
I also removed the CityId column, because generally surrogate id’s are meaningless.

Insert Into TABLE from 3 separate tables

I am getting my face kicked in....
I have a total of 4 tables
1. Business (BusinessID, CustomerID, BusName, Territory)
2. Customer (CustomerID, Name)
3. Sales (BusinessID, CustomerID, Territory, Jan, Feb, Mar, Apr, May, Jun)
4. Performance (this is the table I want the info in)
I've already created the table to have the following columns, BusinessID, CustomerID, BusName, Name, Territory, Jan,Feb,Mar,Apr,May,Jun
Every time I try to insert its not properly joining and I am getting a bunch of errors "multi-part identifier could not be bound"
insert into Performance (BusinessID, CustomerID, BusName, Name, Territory, January2018, February2018, March2018, April2018, May2018, June2018)
select Business.BusinessID, Customer.CustomerID, Business.BusName, Customer.Name, Sales.Territory, Sales.January2018, Sales.February2018, Sales.March2018, Sales.April2018, Sales.May2018, Sales.June2018
from Business A
inner join Customer B ON a.CustomerID = b.CustomerID
inner join Sales C ON b.CustomerID = c.CustomerID;
Due to this error I had to do 3 seperate insert into and that caused a bunch of nulls....
face palm is happening and could use some advice.
Image: enter image description here
Thanks,
VeryNew2SQL
You have used table ALIASES, so you have to use those aliases in you SELECT
A for Business, B for Customer and C for Sales.
Read about ALIASES here.
select A.BusinessID, B.CustomerID, A.BusName, B.Name, C.Territory, C.January2018, C.February2018, C.March2018, C.April2018, C.May2018, C.June2018
from Business A
inner join Customer B ON a.CustomerID = b.CustomerID
inner join Sales C ON b.CustomerID = c.CustomerID;
When you create a table alias in your FROM and JOIN clauses, you need to refer to the aliases in your SELECT statement and not the actual table names.
Alternatively, leave your SELECT statement as it is, and adjust your table names to remove the alias. You'll then need the join conditions to refer to your actual table names, rather than the alias. So for example;
select Business.BusinessID, Customer.CustomerID, Business.BusName, Customer.Name, Sales.Territory, Sales.January2018, Sales.February2018, Sales.March2018, Sales.April2018, Sales.May2018, Sales.June2018
from Business
inner join Customer ON Business.CustomerID = Customer.CustomerID
inner join Sales ON Customer.CustomerID = Sales.CustomerID;
Even just try running the SELECT statement above first to make sure you get the query correct before trying it in your insert.

How to create a temporary table or CTE with values from two sources

Need to build a temporary table or a CTE for reporting purposes. Users will be able to select a location and courses from drop-downs.
The tables involved are the Person table that holds all employees and a Common Table Expression that will have the courses selected from drop down.
I need to be able to create a temporary table or a CTE with employee id field from the person table and a course name field from Course CTE.
For example, if courses A, B, C are selected each employee will have three records, one for each Course selected. So employee 1 will have three records in this temporary table or CTE. I'm using SQL Server 2008.
You can use INNER JOIN or UNION queries inside CTE to get values from Multiple Tables. So If you want to get the EMployeeId and CourseName for Each employee, YOu can Join the tables inside the CTE like this
;WITH CTE
AS
(
SELECT
E.EmployeeId,
C.CourseNm
FROM dbo.Employee E
INNER JOIN dbo.Course C
ON E.CourseId = C.CourseId
)
SELECT
*
FROM CTE
if you want to use Temp tables, you can try this
SELECT
E.EmployeeId,
C.CourseNm
INTO #Temp
FROM dbo.Employee E
INNER JOIN dbo.Course C
ON E.CourseId = C.CourseId
SELECT * FROM #Temp

How do I build a query that crosses multiple tables?

Here are my tables:
CUSTOMER
Cust_ID (PK)
Name
ORDERS
Order_ID (PK)
Cust_ID (FK)
ORDER_LINE
Order_ID (pk)
Part_ID (FK)
PART
Part_ID (PK)
Part_Description
Now I want to list the customer details, the part number and the description of the parts that each customer ordered.
How do i do this?
Thanks.
You should use "JOIN" using the FK, but from what I see you don't have a foreign key between "ORDERS" and "ORDER_LINE". Are you sure you're not missing something from the table definition, ie: ORDER_LINE should maybe have the ORDER_ID as a FK ?
Hope this helps
You can try something like
SELECT c.*,
p.*
FROM CUSTOMER c INNER JOIN
ORDERS o ON c.Cust_ID = o.Cust_ID INNER JOIN
ORDER_LINE ol ON o.Order_ID = ol.Order_Number INNER JOIN
PART p ON ol.Part_Number = p.Part_Number
Have a look at
Join (SQL)
An SQL join clause combines records from two or more tables in a
database.
SQL Joins
The JOIN keyword is used in an SQL statement to query data from two or
more tables, based on a relationship between certain columns in these
tables.
And for some graphic examples
JOIN Basics
What you need is a simple straightforward JOIN like so:
SELECT
c.Cust_ID,
c.Name,
l.Part_Number,
l.Part_Description
FROM CUSTOMER c
INNER JOIN ORDERS o ON c.Cust_ID = o.Cust_ID
INNER JOIN ORDER_LINE ol ON o.OrdeR_ID = ol.Order_Number
INNER JOIN PART l ON ol.Part_Number = l.Part_Number
You want an SQL "join", such as:
SELECT c.Name, ol.Part_Number, p.Part_Description
FROM Customer AS c
JOIN Orders AS o ON c.Cust_ID = o.Cust_ID
JOIN Order_Line AS ol ON o.Order_ID = ol.Order_Number
JOIN Part AS p ON ol.Part_Number = p.Part_Number
Be aware that without a WHERE clause, this query will return all all parts in all orders for all customers, which will really hammer the network and perform poorly on anything but a tiny database:
WHERE (c.Cust_ID = MyCustomerID)
MySQL join syntax
SQL Server join syntax

Resources