Using While SQL Server - sql

I have two tables and both contains columns Names and ID_Number.
table1 contains columns Names, ID_Number, Price_date
table2 contains columns Names, ID_Number, historical_date, comments
I am trying to do a loop such that it will start from the first value in ID_Number column in table1 and see if it matches with any value in ID_number column in table2.
If there is a match, then compare the 'Names' for the two tables for that particular ID_number. If the names does not matched, then in the comments column, enter the Name from table1 and enter the Price_date from table1 to historical_date in table2.

Don't use loops in SQL, as long as you can avoid them. SQL is a set-based language, that is not optimized for iterative processes.
From your explanation, it seems like you want an update statement with a join. This should do what you want:
update t2
set t2.comments = t1.names, t2.historical_date = t1.price_date
from table2 t2
inner join table1 t1
on t1.id_number = t2.id_number
and t1.names <> t2.names

Related

How to JOIN and get data from either table based on specific logics?

Let's say I have 2 tables as shown below:
Table 1:
Table 2:
I want to join the 2 tables together so that the output table will have a "date" column, a "hrs_billed_v1" column from table1, and a "hrs_billed_v2" column from table2. Sometimes a date only exists in one of the tables, and sometimes a date exists in both tables. If a date exists in both table1 and table2, then I want to allocate the hrs_billed_v1 from table1 and hrs_billed_v2 from table2 to the output table.
So the ideal result will look like this:
I've tried "FULL OUTPUT JOIN" but it returned some null values for "date" in the output table. Below is the query I wrote:
SELECT
DISTINCT CASE WHEN table1.date is null then table2.date WHEN table2.date is null then table1.date end as date,
CASE WHEN table1.hrs_billed_v1 is null then 0 else table1.hrs_billed_v1 END AS hrs_billed_v1,
CASE WHEN table2.hrs_billed_v2 is null then 0 else table2.hrs_billed_v2 END AS hrs_billed_v2
FROM table1
FULL OUTER JOIN table2 ON table1.common = table2.common
Note that the "common" column where I use to join table1 and table2 on is just a constant string that exists in both tables.
Any advice would be greatly appreciated!
A full join is indeed what you want. I think that would be:
select
common,
date,
coalesce(t1.hrs_billed_v1, 0) as hrs_billed_v1,
coalesce(t2.hrs_billed_v2, 0) as hrs_billed_v2
from table1 t1
full join table2 t2 using (common, date)
Rationale:
you don't show what common is; your data indicates that you want to match rows of the same date - so I put both in the join condition; you might need to adapat that
there should really be no need for distinct
coalesce() is much shorter than the case expressions
using () is handy to express the join condition when the columns to match have the same name in both tables

Cross joining tables to see which partners in one table have a report from another table [duplicate]

table1 (id, name)
table2 (id, name)
Query:
SELECT name
FROM table2
-- that are not in table1 already
SELECT t1.name
FROM table1 t1
LEFT JOIN table2 t2 ON t2.name = t1.name
WHERE t2.name IS NULL
Q: What is happening here?
A: Conceptually, we select all rows from table1 and for each row we attempt to find a row in table2 with the same value for the name column. If there is no such row, we just leave the table2 portion of our result empty for that row. Then we constrain our selection by picking only those rows in the result where the matching row does not exist. Finally, We ignore all fields from our result except for the name column (the one we are sure that exists, from table1).
While it may not be the most performant method possible in all cases, it should work in basically every database engine ever that attempts to implement ANSI 92 SQL
You can either do
SELECT name
FROM table2
WHERE name NOT IN
(SELECT name
FROM table1)
or
SELECT name
FROM table2
WHERE NOT EXISTS
(SELECT *
FROM table1
WHERE table1.name = table2.name)
See this question for 3 techniques to accomplish this
I don't have enough rep points to vote up froadie's answer. But I have to disagree with the comments on Kris's answer. The following answer:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT name
FROM table1)
Is FAR more efficient in practice. I don't know why, but I'm running it against 800k+ records and the difference is tremendous with the advantage given to the 2nd answer posted above. Just my $0.02.
SELECT <column_list>
FROM TABLEA a
LEFTJOIN TABLEB b
ON a.Key = b.Key
WHERE b.Key IS NULL;
https://www.cloudways.com/blog/how-to-join-two-tables-mysql/
This is pure set theory which you can achieve with the minus operation.
select id, name from table1
minus
select id, name from table2
Here's what worked best for me.
SELECT *
FROM #T1
EXCEPT
SELECT a.*
FROM #T1 a
JOIN #T2 b ON a.ID = b.ID
This was more than twice as fast as any other method I tried.
Watch out for pitfalls. If the field Name in Table1 contain Nulls you are in for surprises.
Better is:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT ISNULL(name ,'')
FROM table1)
You can use EXCEPT in mssql or MINUS in oracle, they are identical according to :
http://blog.sqlauthority.com/2008/08/07/sql-server-except-clause-in-sql-server-is-similar-to-minus-clause-in-oracle/
That work sharp for me
SELECT *
FROM [dbo].[table1] t1
LEFT JOIN [dbo].[table2] t2 ON t1.[t1_ID] = t2.[t2_ID]
WHERE t2.[t2_ID] IS NULL
You can use following query structure :
SELECT t1.name FROM table1 t1 JOIN table2 t2 ON t2.fk_id != t1.id;
table1 :
id
name
1
Amit
2
Sagar
table2 :
id
fk_id
email
1
1
amit#ma.com
Output:
name
Sagar
All the above queries are incredibly slow on big tables. A change of strategy is needed. Here there is the code I used for a DB of mine, you can transliterate changing the fields and table names.
This is the strategy: you create two implicit temporary tables and make a union of them.
The first temporary table comes from a selection of all the rows of the first original table the fields of which you wanna control that are NOT present in the second original table.
The second implicit temporary table contains all the rows of the two original tables that have a match on identical values of the column/field you wanna control.
The result of the union is a table that has more than one row with the same control field value in case there is a match for that value on the two original tables (one coming from the first select, the second coming from the second select) and just one row with the control column value in case of the value of the first original table not matching any value of the second original table.
You group and count. When the count is 1 there is not match and, finally, you select just the rows with the count equal to 1.
Seems not elegant, but it is orders of magnitude faster than all the above solutions.
IMPORTANT NOTE: enable the INDEX on the columns to be checked.
SELECT name, source, id
FROM
(
SELECT name, "active_ingredients" as source, active_ingredients.id as id
FROM active_ingredients
UNION ALL
SELECT active_ingredients.name as name, "UNII_database" as source, temp_active_ingredients_aliases.id as id
FROM active_ingredients
INNER JOIN temp_active_ingredients_aliases ON temp_active_ingredients_aliases.alias_name = active_ingredients.name
) tbl
GROUP BY name
HAVING count(*) = 1
ORDER BY name
See query:
SELECT * FROM Table1 WHERE
id NOT IN (SELECT
e.id
FROM
Table1 e
INNER JOIN
Table2 s ON e.id = s.id);
Conceptually would be: Fetching the matching records in subquery and then in main query fetching the records which are not in subquery.
First define alias of table like t1 and t2.
After that get record of second table.
After that match that record using where condition:
SELECT name FROM table2 as t2
WHERE NOT EXISTS (SELECT * FROM table1 as t1 WHERE t1.name = t2.name)
I'm going to repost (since I'm not cool enough yet to comment) in the correct answer....in case anyone else thought it needed better explaining.
SELECT temp_table_1.name
FROM original_table_1 temp_table_1
LEFT JOIN original_table_2 temp_table_2 ON temp_table_2.name = temp_table_1.name
WHERE temp_table_2.name IS NULL
And I've seen syntax in FROM needing commas between table names in mySQL but in sqlLite it seemed to prefer the space.
The bottom line is when you use bad variable names it leaves questions. My variables should make more sense. And someone should explain why we need a comma or no comma.
I tried all solutions above but they did not work in my case. The following query worked for me.
SELECT NAME
FROM table_1
WHERE NAME NOT IN
(SELECT a.NAME
FROM table_1 AS a
LEFT JOIN table_2 AS b
ON a.NAME = b.NAME
WHERE any further condition);

SQL query from three tables, using the results from the first table

I am having trouble with queries from multiple tables. My platform is SQL. The first two columns of each table (ID, Tag) are related to each other. I am trying to select data from table2 and table3 using the results from table1.
Table1 is used to determine the ID and Tag. The combination of ID and Tag is unique for this table. There are no null values in table1. In this example, I will search for the ID and Tag using the Top Weight and Bottom Weight. However, any number of criteria can be used to find the ID and Tag.
SELECT ID, Tag FROM table1 WHERE Top Weight = '22' AND Bottom Weight = '44'
I would like to take the ID and Tag results from table1, and use them for my table2 and table3 queries. For table2, the combination of the first two columns (ID, Tag) is unique. I would like to select Color, Shade, and Tint from this table. There can be null values for these columns. For table3, the combination of the first three columns (ID, Tag, Sequence) is unique. I would like to select Sequence, Length, and Width from this table. These columns can also have null values.
Is it possible to combine all three tables into a single query, and use the results of the first table to get the results of the second and third table? The example tables are only 14 rows, but in reality, there are tens of thousands of rows – so performance is critical (when is it not?). I look forward to your response, thanks.
This looks like a fairly straightforward outer join query:
select t1.id, t1.tag,
t2.Color, t2.Shade, t2.Tint,
t3.Sequence, t3.Length, t3.Width
from table1 t1
left join table2 t2 on t1.id = t2.id and t1.tag = t2.tag
left join table3 t3 on t1.id = t3.id and t1.tag = t3.tag
WHERE t1.[Top Weight] = '22' AND t1.[Bottom Weight] = '44'

SQL statement selecting rows from a table dependent on information from another table

I have two different tables in a database, differing in number of columns. Now, I want to select a number of rows from the first table dependent on some variable (for example that the first column should have the value 1). However, I would also like to use information from my other table to select rows from my first table.
In my specific case, both table1 and table2contains the columns Group and Person. Table1 specify each person once, and declares what group he or she belongs to. However, people can also be part of secondary groups, which are listed in table2. That is, in table2, a person can be listed again with a new group number.
I would like to write an SQL statement where I select persons (that is, rows) from table1 (since I have more information about the persons in this table) that are members of a certain group, x. However, since a person can belong to several groups, I need to look through table2 as well, somehow.
How can I write this SQL statement?
select t1.person_id,t1.group_id
from table1
union all
select t2.person_id,t2.group_id
from table2
this will give you one table
person group
person1 group1
person1 group2
person2 group3
no matter what tables they belong to.
This architecture seems silly however if the same data is in both tables.
If i have understood your question correctly, this query below will get you a person's details where the person is a member of a group 'X' and that relationship between person and that particular group 'X'is coming from a record maintained in either table1 or table2.
SELECT t1.*
FROM table1 t1
LEFT OUTER JOIN table2 t2
ON t1.Person = t2.Person
WHERE t1.Person = 'Y'
AND (t1.Group = 'X' OR t2.Group = 'X')
You will need some sort of identifier in both tables - like a candidate key.
When you do your select you need to join the tables, example:
SELECT column_name(s)
FROM Table1 table_name1
INNER JOIN Table2 table_name2
ON table_name1.column_name=table_name2.column_name
WHERE table_name1.person = table_name2.person
You can use JOIN clause to combine rows from two or more tables, based on a related column between them.
Let's look at a selection in this example:
SELECT
       table1.user_name,
       table2.group_name,
       table1.address
FROM table1
INNER JOIN table2
ON table1.UserID = table2.ID;

Help with Joins

my first table has about 18K records
so when i
select * from table2 i get about 18k
i'm trying to do a join on it as follows, but i'm getting like 26K back.. what am i doing wrong? i though it's supposed to return all of the "right" aka table2 records plus show me whatever value matches from the first in a separate column...
Select t1.fID , t2.*
FROM table1 t1 right join table2 t2 on t1.fName = t2.f
here is an exmaple of my tables:
table 1:
fID, fName
table 2: id, f, address, etc
i need to get all records from table 2, with an fID column, whenever f=fName
table1 has many rows with a value of fname that matches the same in table2.
Example, say 5k rows table2 have no matching rows in table1, you have a average of 2 rows in table 1 for each of the remaining 13k table2 rows
Because you have also asked for a column for table1, this will happen. You'll note multiple t1.fId values for a given t2.fname. Or NULLs
If t1.fName and t2.f aren't unique identifiers for their tables, you will find that rows from table1 are being joined with multiple rows from table2.
The RIGHT JOIN keyword Return all rows from the right table (table_name2), even if there are no matches in the left table (table_name1).See Right Join
So it looks like you do not have your matching criteria set correctly or you have no matches.
This is possible when some fName values are repeated in Table2 and/or Table 1.
Run these Queries and See:
SELECT fName, COUNT(1) FROM Table2 GROUP BY fName HAVING COUNT(1) > 1
SELECT fName, COUNT(1) FROM Table1 GROUP BY fName HAVING COUNT(1) > 1