How to put join result into a new table - sql

How do I put the result of this join query into a new table on the same schema?
SELECT census2010.district,census2010.total,census2010.male,
census2010.female,census2010.region, districts.area
FROM ghana.census2010 LEFT JOIN ghana.districts
ON census2010.region ILIKE districts.region

Considering the above code, use the CREATE TABLE ___ AS ( )
command. like this
CREATE TABLE ghana.TableName AS (
SELECT census2010.district,census2010.total,census2010.male,
census2010.female,census2010.region, districts.area
FROM ghana.census2010
LEFT JOIN ghana.districts ON census2010.region ILIKE districts.region)
The result should be a table in the same database schema

If you want your join table to evolve after new entries are added or removed from your two starting tables, creating a view is the appropriate choice.
CREATE VIEW view_name AS
SELECT census2010.district, census2010.total, census2010.male,
census2010.female, census2010.region, districts.area
FROM ghana.census2010
LEFT JOIN ghana.districts
ON census2010.region ILIKE districts.region);
Then, you'll be able to run queries like the following ones
SELECT * FROM view_name;
in order to obtain the always up-to-date joined table. You can remove a view like any other table by running:
DROP VIEW view_name;

Related

CREATE TABLE a third table from two tables JOIN statement

I have 2 tables and want to create a third one when ta asin_id and tb asin have the same value,
with the
SELECT * FROM ta JOIN tb ON ta.asin_id = tb.asin;
i can have the view from the third table but i cant create it.
i already tried this:
CREATE TABLE tc AS SELECT * FROM ta JOIN tb ON ta.asin_id = tb.asin;
ERROR: syntax error at or near "tc"
LINE 1: CREATE tc AS SELECT * FROM items JOIN bs_audiotv ON items.as...
i attached a pic from the shell here: https://photos.app.goo.gl/LLjHi2wn9WQhxXkR8
CREATE T is not a right syntax. You have to use CREATE TABLE TABLE_NAME AS
When you are using CTAS you should specify which columns you need one by one. If same column name exists in your tables then you will receive an error again.
CTAS
Here is you script.
CREATE TABLE TC
AS
SELECT ITEMS.ASIN_ID,
ITEMS.TITLE,
ITEMS.BRAND,
ITEMS.DESCRIPTION,
ITEMS.CATEGORIES,
ITEMS.SPECIFICATIONS,
ITEMS.IMAGES,
BS_AUDIOTV.ASIN,
BS_AUDIOTV.LINK,
BS_AUDIOTV.PRICE_L,
BS_AUDIOTV.PRICE_U,
BS_AUDIOTV.PRICE
FROM ITEMS JOIN BS_AUDIOTV ON ITEMS.ASIN_ID = BS_AUDIOTV.ASIN;

How to create a table with multiple columns

Struggling with a create table statement which is based on this select into statement below:
#MaxAPDRefundAmount money = 13.00
...
select pkd.*, pd.ProviderReference, per.FirstName, per.Surname, #MaxAPDRefundAmount [MaxAPDRefundAmount],commission.Type [Commission] into #StagedData from CTE_PackageData pkd
inner join J2H.dbo.Package pk on pkd.Reference = pk.Reference
inner join J2H.dbo.Product pd on pk.PackageId = pd.PackageId
inner join J2H.dbo.FlightReservation fr on pd.ProductId = fr.ProductId
and fr.FlightBoundID = 1
inner join J2H.dbo.ProductPerson pp on pd.ProductId = pp.ProductID
and pp.StatusId < 7
inner join J2H.dbo.Flight f on fr.FlightId = f.FlightID
inner join J2H.dbo.Person per on pk.PackageId = per.PackageId
and per.PersonId = pp.PersonId
inner join J2H.dbo.PersonType pt on per.PersonTypeId = pt.PersonTypeID
We are changing a select into to just normal insert and select, so need a create table (we are going to create a temp (hash tag table) and not declaring a variable table. Also there is a pkd.* at the start as well so I am confused in knowing which fields to include in the create table. Do I include all the fields in the select statement into the create statement?
Update:
So virtually I know I need to include the data types below but I can just do:
create table #StagedData
(
pkd.*,
pd.ProviderReference,
per.FirstName,
per.Surname,
#MaxAPDRefundAmount [MaxAPDRefundAmount],
commission
)
"Do I include all the fields in the select statement into the create statement?" Well, that depends, if you need them, than yes, if not than no. It's impossible for us to say whether you need them... If you're running this exact query as insert, than yes.
As for the create statement, you can run the query you have, but replace into #StagedData with something like into TEMP_StagedData. In management studio you can let sql server build the create query for you: right-click the newly created TEMP_StagedData table in the object explorer (remember to refresh), script Table as, CREATE To and select New Query Editor Window.
The documentation of the CREATE TABLE statement is pretty straightforward.
No. Clearly, you cannot use pkd.* in a create table statement.
What you can do is run your old SELECT INTO statement as a straight SELECT (remove the INTO #stagedata) part, and look at the columns that get returned by the SELECT.
Then write a CREATE TABLE statement that includes those columns.
To create a table from a SELECT without inserting data, add a WHERE clause that never returns True.
Like this:
SELECT * INTO #TempTable FROM Table WHERE 1=0
Once the table with the columns for your SELECT, you can add additional columns with ALTER TABLE.
ALTER TABLE #TempTable ALL ExtraColumn INT
Then do your INSERT/SELECT.

How to span mulitiple tables with a view, when the tables have same structure

So we have a db that receives constant input and then we have it moved after x days to a different db as a type of archive/reporting db. So the question is when I try to create a view that combines two of the tables (one from each db):
CREATE VIEW Table_Full AS
SELECT *
FROM [Front].dbo.[DATA] AS A
Inner Join Back.dbo.DATA AS B
ON A.DATETIME=B.DATETIME
I get the following error: "Column names in each view or function must be unique. Column name 'PARTNO' in view or function 'Table_Full' is specified more than once."
So, is there a better way to accomplish what I am trying to do or ?
Given your use case, I think you want a union. That is
select * from table_a
Union all
Select * from table_b
Instead of an asterisk, you have to specify each field and provide aliases for the duplicate field names:
CREATE VIEW Table_Full AS
SELECT
a.ID as A_ID,
b.ID as B_ID,
a.Thingy as A_Thingy,
a.Etcetera as Atcetera
FROM [Front].dbo.[DATA] AS A
Inner Join Back.dbo.DATA AS B
ON A.DATETIME=B.DATETIME

Postgres - CREATE TABLE FROM SELECT

I have two tables, one contains a large list of IDs and Info regarding those ids.
I have a second table Graph which just has two columns, each column contains the aforementioned id numbers, multiple times. I want to trim the size of my Info table by selecting only those ids that appear in my graph and creating a new smaller Info table. Is there a simple way of doing this?
CREATE TABLE FROM SELECT?
Thanks!
It's as easy as:
create table new_table
as
select t1.col1, t2.col2
from some_table t1
join t2 on t1.id = t2.some_id;
You can use any select statement for that. The column names of the new table are defined by the column aliases used in th query.
More details in the manual: http://www.postgresql.org/docs/current/static/sql-createtableas.html
You can create TEMP table if you need those small table only for that session. you can use below query to do that.
DROP TABLE IF EXISTS temp_table;
CREATE TEMP TABLE temp_table AS
SELECT
i.id as info_id, i.information as information
FROM
info i
INNER JOIN graph g ON i.id = g.id;
Now you can use this temp_table for your next table in the function.
OR
you can also create table like below (if you not want to create it as TEMP):
CREATE TABLE temp_table AS
SELECT
i.id as info_id, i.information as information
FROM
info i
INNER JOIN graph g ON i.id = g.id;

Referring to other SQL scripts from a SQL script?

I'm currently converting MS access queries to SQL queries and noticed that in the access query it appears to be joining another query to other tables. So I looked around and it seems like that query pretty much makes the query look cleaner without needing to have all sorts of subqueries in the same script
Something like
FROM [query name] INNER JOIN [some other table]
Is there something like this in SQL?
You are probably looking for VIEWS.
A view is basically a stored version of a SELECT query. It allows you to reference the result set without rewriting the query every time.
You can create a VIEW as a query, then reference the view in another query.
CREATE VIEW <viewname> AS <SELECT STATEMENT>
then
SELECT * FROM <viewname> INNER JOIN <other table>
Yes. They are called views.
You can create a view like
CREATE VIEW vw_some_query AS
SELECT * FROM
table_a LEFT INNER JOIN table_b ON table_a.id = table_b.id2
then you can write a select like:
SELECT * FROM vw_some_query LEFT INNER JOIN table_c ON vw_some_query.id = table_c.id3
Is there something like this in SQL?
Yes. In SQL you would probably use the WITH clause:
WITH someData AS
(
select a.col1, b.col2
from tableA a join tableB b
on (a.someKey = b.someKey)
),
...
select data1.col1, data1.col2, data2.col3
from someData data1 join tableC data2
on (data1.col1 = data2.anotherKey)
where ...
Views are ok too, but another db object to keep track of, and if using a materialized view, need to worry about refreshing snapshot table, etc. My suggestion is to use WITH along with plenty of comments where possible.
EDIT: If you find yourself asking the same question of the db over and over, then a view (or mat view) would be more appropriate. But otherwise, keep logic in the query.