Multiple SQL Joins on Two Tables - sql-server

I need to create 1 table based on matching the records of two tables, lets call them table p and table c, in SQL Server. The manual way to do this in Excel is to match the Order Column in table p with the Order Column in table c. Once those are matched, you take the corresponding Batch Column in table c and match it with the Batch Column in table p. Once those are matched you then take that corresponding Order Column in table p and match it with table c again and thats the final item we want to pull. Any ideas?

It's hard to say for sure given the lack of table definitions, but it sounds as though you need to do two joins, once over to table c, then back again to table p, which you would alias in order to pull the right column value. Perhaps this will help you get started.
SELECT p1.Order
FROM p
INNER JOIN C
ON p.Order = c.Order
INNER JOIN p as p1
ON p1.brance = c.branch

Related

How to get query result in multiple columns in Postgres?

I am new to Postgres. I have a table which has the data in the below format:
Table Data
And I want it in the following format. Any help would be appreciated.
Output Format
You can accomplish this with a self-join:
SELECT table_2184."Value" as "2184",
table_2095."Value" as "2095",
table_2184."Date_Time"
FROM table AS table_2184
JOIN table AS table_2095 ON table_2184."Date_Time" = table_2095."Date_Time"
WHERE table_2184."Tag_ID" = 2184
AND table_2095."Tag_ID" = 2095;
Basically, you alias the table so you can join it to itself. If it's not always guaranteed that the tags exist at the same timestamp, you may want to use a FULL OUTER JOIN instead of a JOIN. In that case, also move the WHERE condition to the join.

SQL: Use a loop to generate X number of TEMP tables, then join X number of temp tables

I need to create a flexible query, which will loop and generate X number of temp tables. Following the loop, the query will then be able to join all X of these temp tables.
Thus, I need a query that can generate 1,2,3,...,n temp tables, and then be able to join all of them, no matter the amount. They will all be join on an 'ID' PRIMARY KEY, with each table having the EXACT same ID values...
Thank you in advance!
Sounds to me like you need stored procedures.
And then in the stored procedure you create a variable where you dynamically create your join query.
And then you use exec to run the contents of the variable.
It's considered very bad practice but it make it possible to do some things that would normally be impossible, most notably return different number of columns depending on the data.

Number of rows updated in a oracle table

I have a table called t1 which is already updated by a file. I have table t2 which is created as backup for table t1 before modifications. Now I want to know how many records got updated in table t1. Is there anyway that I can do join with back up table and know how many records got altered? Or how to use sql%rowcount function on a already updated table? Or how should i proceed with ALL_TAB_MODIFICATIONS?
You can join the tables on their primary key (cos you didn't update that, hopefully!) and then compare every column.. you'll have to check for nulls too, and it'll make quite a lot of typing. You could use all_tab_cols and a bit of sql to create your query though (write an sql that creates sql as its output )
Actually, thinking about it, you might be able to get away with less typing by doing a natural join the tables together to get a set of rows that didn't change and removing that set from the original full set:
select * from original
Minus
select original.* from original natural inner join backup
Ive never done it, but the theory is that natural join joins on all equal column names so every column of each table will feature in the join condition. It's an inner join so only columns that have not changed will be represented. Any columns that have become null or become valued from null will also disappear. This is hence the set of rows that have not changed. If all you're after is a count, do a count of the original table less the count of this join result. If you want to know which rows changed, do the result set minus.
Ideally you shouldn't do this; instead at the point the update is run, capture the number of rows it affected. However, this technique could be used long after the update was performed (but before some other update was run)

Prefix in field name SQL

I am an extreme rookie when it comes to SQL and I am trying to self teach myself. I have a few questions regarding SQL and writing queries:
I've been given some examples of queries by a colleague and many of them have the field names beginning with either m. or t. or o.email (eg. m.email or t.email or o.email). What do the prefixes indicate?
I am attempting to write a JOIN query but keep receiving an error message saying: An expression of non-boolean type specified in a context where a condition is expected, near ')' What would cause this? Neither of the data extensions I am trying to join contain boonlean fields.
I've written it as:
SELECT DISTINCT email, status_type, status_value_text FROM ent.[Table 1] JOIN [Table 2] ON email
Again, I am extremely new, any help would be greatly appreciated!
The general form of an SQL SELECT query is:
SELECT (columns, expressions, aggregate functions)
FROM (data sources)
WHERE (filters on data sources)
GROUP BY (columns used to group the data, needed if you use aggregate functions)
HAVING (filters on data AFTER it's grouped)
About the FROM clause, if you use more than one data source (table or view), you should think how your data will be related:
A cross join returns the cartesian product of the tables involved.Example:
FROM foo, bar will return all the rows of table foo and all the rows from table bar, without any rule on how they are related.
An inner join returns only the data that fulfills a relation rule.
Example:
FROM foo INNER JOIN bar ON foo.aField = bar.aField (alternative: FROM foo JOIN bar ON foo.aField = b.aField) will return only the rows of foo and bar that fulfils the condition provided (the field aField in each table must match). Important: An INNER JOIN must have a boolean expression, i.e. the relation must either be true or false; most times it will be an equality relationship (=) but it can be anything that returns a TRUE/FALSE value (>, <, >=, etcetera).
An outer join returns the full data of one table and only the rows of the other table that match the relation rule (for any other non-matching row of the first table, the columns from the second table will have a NULL value).
There are two possible outer joins: LEFT JOIN will return all the rows from the table on the left of the relation rule, and only the matching rows of the right table of the relation. RIGHT JOIN does just the opposite.
Example:
FROM foo LEFT JOIN bar ON foo.aField = bar.aField
As it was the case with the INNER JOIN, the relation must have a boolean expression.
Now, as you've noticed, you need to tell the system from which field you're getting the data. That's the reason for the "prefixes": They are the table (or schema.database.table) names. If you want, you can use aliases on this table names (just as you can use aliases on fields):
Example: FROM foo AS f INNER JOIN bar AS b on f.aField = b.aField
The aliases used in the FROM clause must be used every time you use the field in the same SELECT query.
Now, talking explicitly about your query: The JOIN in your post is missing the relation rule: You're telling the database server that the tables are related, but you're not defining the relation rule. Wich fields must match? Complete the JOIN expression with the columns that must match between the tables.
What do the prefixes indicate?
If you look at the FROM clause of the example queries you are questioning, you should notice table aliases specified after the full table names. Aliases are used sometimes just to shorten the table names from needing to be fully spelled out, but most often they are needed to disambiguate between similarly named columns in more than one of the tables in the FROM.
SELECT
-- Get the email column from the table aliased
-- as `m` (table1)
m.email
FROM
-- table1 aliased as m
table1 AS m
-- table1 aliased as e
INNER JOIN table2 AS e ON....
Consider two related tables, table1 and table2. Both of them has a column called email. In the SELECT list, you may not specify merely email because the RDBMS won't know which one you want. Instead, you must qualify it with the table name. Since the tables were aliased as m, e in the FROM, you must use the alias in SELECT instead of the full table name.
MS SQL Server documentation on table aliases...
An expression of non-boolean type specified in a context where a condition is expected, near ')'
In your join's ON clause, you simply supplied the column name email, which we can assume is a common value relating the two tables. A join's ON clause expects a boolean expression wherein a true value doing a row-wise comparison between the tables results in a row being returned.
So the ON clause needs a boolean expression with two sides, or something returning TRUE. In your case, it is equality between the email columns
SELECT DISTINCT
-- Must qualify email since both tables have it
-- Using the full table name, or its alias if an alias
-- was provided in `FROM`.
[Table 1].email,
status_type,
status_value_text
FROM
ent.[Table 1]
-- Equality between email columns completes the join
JOIN [Table 2] ON [Table 1].email = [Table 2].email
The expression in ON can be anything which evaluates to TRUE. It need not be an exact match between column values, though an exact match is by far the most common use case. You could say for example ON 1 = 1, which is always true. The resultant rowset would match every row from [Table 1] to every row of [Table 2] (which is a cartesian product). It could also be ON 1 = 2 which is never true, and therefore basically pointless since it would never return rows.
Using a syntax similar to the ON email you attempted, some RDBMS systems support a USING() in place of ON, allowing you to specify the equal column instead of a boolean expression. You might therefore also express it as
FROM
ent.[Table 1]
JOIN [Table 2] USING (email)
See also What's the difference between ON and USING
The m. or t. are aliases for tables within your query (so you are probably using tables that begin with the letter m and t). The alias is specified after the table name in the FROM part of your query.
The syntax looks off for your JOIN. The query should probably look more similar to this:
SELECT DISTINCT t1.email, t1.status_type, t2.status_value_text
FROM
[Table 1] t1 JOIN [Table 2] t2 ON t1.email = t2.email
Check out this link to see more examples.http://www.w3schools.com/sql/sql_join.asp

Creating a procedure for creating a table with dynamic number of columns

I'm trying to create a procedure that can create a table with not specific number of columns.
My query returns a value of 3 meaning it needs 3 columns (has to be dynamic).
I have create a #variable to set the name string of the tables but I don't know how to formulate the CREATE TABLE statement to actually create the table with the columns from this string.
Any kind of help would be appreciated guys.
You can get the columns on a table out of the sql database with
select
bb.name,
bb.colid
from sysobjects aa
inner join syscolumns bb
on aa.id = bb.id
where aa.name ='tblMyTable'
The name is the column name, the ID the number. You could select column names from the list and use dynamic sql to build a select. Not sure how you decide what columns you are after from the table.

Resources