Append data from table one to another - Syntax error? - sql

I have two tables of zip code information, one without city and state fields (2016_Zips), the other is just a list (USZips_V1) of zip codes, the “Zip_Code” field is common in both tables.
I'd like to match the more complete data (with fields for city, state, latitude, longitude, etc) to the basic list of zip codes.
This way I can see which zip codes are common for which city (big cities have multiple zip codes).
This is the code I have, but returns:
Syntax error in expression 2016_Zips.Zip_Code
SELECT USZips_V1.Zip_Code, 2016_Zips.Zip_Code, USZips_V1.city, USZips_V1.state_id, 2016_Zips.lat, 2016_Zips.long, USZips_V1.imprecise, USZips_V1.military
FROM USZips_V1
INNER JOIN 2016_Zips ON USZips_V1.Zip_Code, 2016_Zips.Zip_Code;
and based it off of this:
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
Here are my table headings:
This is where I want the information added:
This will be where I draw the data from to add to the table above:
Is there a better way to do what I want to do? Is there a glaring error in my statement?
My goal in doing this is to save time matching data between the tables.
This is my expected output:

Always use Explicit JOIN
SELECT u.Zip_Code, z.Zip_Code, u.city, z.state_id, z.lat, z.long, u.imprecise, z.military
FROM USZips_V1 AS u
INNER JOIN 2016_Zips AS z ON u.Zip_Code=z.Zip_Code;

you have to use = in your join instead ,
SELECT t1.*,t2.*
FROM USZips_V1 t1
INNER JOIN 2016_Zips t2 ON t1.Zip_Code= t2.Zip_Code;

Related

Finding overlap between two tables, and percentage in SQL

I have two tables.
One with customer information (including Zip Code).
Second is all zip codes around the States.
I am trying to find two things:
Which zip codes overlap from the customer information table and the entire zip codes table?
The percentage of customers per Zip code - so something that overlaps the two tables to see the ratio of customers in each zip code...
I am having a lot of trouble with this. I don't really know where to start. Can anyone advise on a starting point? I am new to SQL.
My initial thought is to have the main query, then the subquery with some sort of a join. But I am struggling to come up with anything.
Edit: Expected output is a column with the overlapping zip codes, and a column with the percentage of customers in that zip code.
With customers, zipcodes your tables; and code the filed for the zipcode in each table, and id some customer id.
Try:
SELECT DISTINCT zipcodes.code from zipcodes LEFT JOIN customers on customers.code = zipcodes.code
for the overlapping zipcodes
and
WITH us_count as (
SELECT COUNT(*) from zipcodes
LEFT JOIN customers ON customers.code = zipcodes.code)
SELECT customers.code, 100 * COUNT(customers.id)/us_count FROM zipcodes LEFT JOIN customers ON customers.code = zipcodes.code GROUP BY customers.code

Sub Queries, Group By's, and Joins

I am new to sql and am trying to complete an assignment for a class where were practicing using subqueries and joins.
The question I'm struggling with is: Provide a list of the airport city names and the travelers (last name) who have traveled to each airport via a flight.
Here are the tables in the database:Database Tables
Here is what I have so far:
SELECT Airport.CityName
FROM AIRPORT
GROUP BY AirportID
INNER JOIN FLIGHT
ON FLIGHT.AirportID = AIRPORT.AirportID
INNER JOIN TRAVELER
ON TRAVELER.TravelerID = FLIGHT.TravelerID
SELECT TravLastName
FROM TRAVELER
but I'm getting an error on the first "Inner" and I know I'm probably nowhere close to being right. Any help would be appreciated.
The joins look fine but there should only be one select at the beginning and the group by should come at the end
SELECT
Airport.CityName,
TRAVELER.TravLastName
FROM AIRPORT
INNER JOIN FLIGHT
ON FLIGHT.AirportID = AIRPORT.AirportID
INNER JOIN TRAVELER
ON TRAVELER.TravelerID = FLIGHT.TravelerID
GROUP BY
Airport.CityName,
TRAVELER.TravLastName;
Or, as we are not using any aggregate functions we can use DISTINCT. It is simpler and can run quicker.
SELECT DISTINCT
Airport.CityName,
TRAVELER.TravLastName
FROM AIRPORT
INNER JOIN FLIGHT
ON FLIGHT.AirportID = AIRPORT.AirportID
INNER JOIN TRAVELER
ON TRAVELER.TravelerID = FLIGHT.TravelerID;
You don't want GROUP BY, you want DISTINCT:
SELECT DISTINCT
AIRPORT.CityName,
TRAVELER.TravLastName
FROM AIRPORT
JOIN FLIGHT ON FLIGHT.AirportID = AIRPORT.AirportID
JOIN TRAVELER ON TRAVELER.TravelerID = FLIGHT.TravelerID
Some tidy ups:
INNER is the default join type, so you can leave it out
DISTINCT means remove duplicates
FROM starts the list of tables to be joined. You can't add tables to the query in other places
A further tidy up would be to use table aliases, which rename the table in the context of the query - often using just the first letter of the table, to make the query smaller overall:
SELECT DISTINCT
a.CityName,
t.TravLastName
FROM AIRPORT a
JOIN FLIGHT f ON f.AirportID = a.AirportID
JOIN TRAVELER t ON t.TravelerID = f.TravelerID
The keyword AS may optionally be put between a table and its alias, eg FROM AIRPORT AS a.

sql query counting something across three tables

I have three tables with some columns shown below:
Table 1 - airports: NAME IATA, COUNTRY
Table 2 - airlines: NAME, IATA
Table 3 - routes: AIRLINE, SOURCE AIRPORT, DESTINATION AIRPORT
I want to write an SQLite query which finds out how many countries certain airlines fly to.
Here's what I've got so far:
SELECT al.NAME AS 'Airline Name',
COUNT(r.AIRLINE) AS 'No. of Destinations'
FROM airlines as al
INNER JOIN routes r ON r.AIRLINE = al.IATA
INNER JOIN airports ap ON r.DESTINATION_AIRPORT = ap.IATA
GROUP BY ap.COUNTRY
ORDER BY [No. of Destinations] DESC;
I'm getting an incredibly wrong result. Help would be appreciated please and thank you. (those joins are the links between the tables for those who want to try and write a query for me)
There are two major problems with your query:
The SELECT columns are inconsistent with the GROUP BY.
You are not counting the countries, which seems to be what you want.
Tweaking your query fixes this problem:
SELECT al.NAME AS Airline_Name,
COUNT(DISTINCT cp.country) AS num_countries
FROM airlines al INNER JOIN
routes r
ON r.AIRLINE = al.IATA INNER JOIN
airports ap
ON r.DESTINATION_AIRPORT = ap.IATA
GROUP BY al.name;
Note: I strongly discourage you from using single quotes for column names. The simplest approach is to use column names that don't require escaping. Then only use single quotes for string and date constants.

Getting repeats of output, possibly doing a join wrong?

I'm having an issue where I'm getting some incorrect values in my output. I am binding the below highlighted table column with the circled column down the bottom. The service_id on the highlighted column is what is unique, but I need to bind the booking_id to retrieve the info (if that makes sense. What I end up getting is the top table where I get repeats, or the price is wrong. I should be getting only 5 lines in the top table.
Here's my code. I suspect I might be doing the join wrong?
SELECT bad.agent as Agents,
dog.SUPPLIER as SUPPLIER,
bad.status as TheStatus,
country.analysis_master1 as Country,
ftb.booking_actual_retail as BookingActualRetail,
ftb.Booking_Actual_Cost as BookingCost,
ftb.Booking_Actual_Retail_inc as BookingRetailINC,
fts.Service_Id,
fts.Service_Actual_Retail_inc as ServiceActualCostInc,
Product.SERVICE,
Product.SL_STATUS as SLSTATUS,
cat.name as Product2,
bad.LAST_SERVICE_DATE as Servicedate,
bad.LW_DATE as LWDATE,
ftb.Entered_Date as DATEENTERED,
ftb.Booking_Pax as PEOPLE,
ftb.Booking_Children as KIDS,
bad.TRAVELDATE as TRAVELDATE,
bad.FULL_REFERENCE
from BHD bad
inner join FTB on bad.FULL_REFERENCE = ftb.booking_reference
inner join FTS on FTB.Booking_Id = fts.Booking_Id
inner join DRM Country on bad.agent = country.code
inner join BSL Product on bad.BHD_ID = Product.BHD_ID
inner join SRV cat on Product.SERVICE = cat.CODE
inner join OPT dog on Product.OPT_ID = dog.OPT_ID
where bad.STATUS = 'IV' AND bad.FULL_REFERENCE = 'LTIT129488'
UPDATE:
Ok, so it looks like this join here causes the multiple outputs:
inner join FTS on FTB.Booking_Id = fts.Booking_Id
I have included the two tables, their headers, and sample data
You have somewhere put the join for the service or supplier in the wrong way.. Please check this line again.
inner join SRV cat on Product.SERVICE = cat.CODE
UPDATED SOLUTION :
As per your updated screenshots, I found the issue...
you have joined like this.
inner join FTB on bad.FULL_REFERENCE = ftb.booking_reference
In this join, your one table has single record against booking reference while another have multiple records against booking refrence. Thats why you are getting the multiple records in the output.
Remove this join and your problem will be solved. If you really want the data from this table then you can select in other way like using outer apply etc.

What letters are written before column titles

I'm learning SQL language using online resources, but mostly using queries that my predecessors have written at my company. I'm editing fields correspondingly to produce the correct results. But I want to understand more.
I have a few questions about this section of code.
1. Why is there a "p" before TrackingNumber, and oh/cc/im in front of others?
It seems to matter which I choose, so I just use trial and error until it runs.
2. Why do I need to have tracking number - when I delete this line, the code won't run!
select
p.TrackingNumber
,im.Sku
,oh.BusinessUnitCode
,cc.Qty
,oh.ShipCode
,oh.OrigShipCode
,oh.Store
,convert(date,oh.ShipTime) as 'OrderDate'
,oh.ShipToName
,oh.OrderNumber
from dmhost.tblOrderHeader oh
join dmhost.tblContainer c on oh.OrderHeaderID = c.OrderHeaderID
join dmhost.tblPackage p on c.ContainerID = p.ContainerID
join dmhost.tblContainerContents cc on c.ContainerID = cc.ContainerID
join dmhost.tblItemMaster im on im.ItemMasterID = cc.ItemMasterID
where (oh.ShipTime between '04/07/2019' and '05/05/2019')
The letters you talk about are referring to table names (or aliases).
Example using aliases would be:
SELECT c.customerName, o.orderNumber from Customers c
INNER JOIN Orders o on c.id=o.customerid
Same query without aliases:
SELECT Customers.customerName, Orders.orderNumber from Customers
INNER JOIN Orders on Customers.id=Orders.customerid
or omitting table names
SELECT customerName, orderNumber from Customers
INNER JOIN Orders on Customers.id=Orders.customerid
The table denomination is specially important when you retrieve columns with the same name from different table. For example id from Customers and id from Orders
SELECT c.id as CustomerId, o.id as OrderId from Customers c
INNER JOIN Orders o on c.id=o.customerid
The bits before the dot (.) in your field names are table aliases. If you look in the FROM clause of this query you should see these abbreviations in front of the various tables listed in there. They're used to
a) make it less tedious to type table names and
b) make it unambiguous which table you are selecting the column from (this both increases readability of the code and also deals with any cases where two of the tables have columns with the same name)
Here's a simple example of table alias usage:
SELECT emp.ID, emp.Name, dep.ID, dep.Name
FROM employees emp
INNER JOIN departments dep ON dep.ID = emp.DepartmentID
Here you can see that the employees and departments tables have each got aliases to shorten their name. In the query we refer to each field using it's alias. This is especially useful since both tables have fields called "ID" and "Name".
As for why it crashes when you remove p.TrackingNumber, it's likely because you did not also remove the comma (,) from the next line. The comma is used to mark where the name of the next field begins - it could be at the end of the previous line, rather than the start of the next one. Clearly you can't start the list of fields with a comma, because there is no field name preceding it - hence you get a syntax error.
The same query could have been written
select
p.TrackingNumber,
im.Sku,
oh.BusinessUnitCode,
-- etc
which might make it easier to see the usage of the comma.