How to join the table - sql-server

Here i have 2 tables and i need to join the table as i am a beginner please help me to solve
Table1 Table2
ins1 ins2 ins3 Insc0
1 2 0 1
3 4 0 2
5 6 0 3
4
5
is this below code right?
select t2.insco from table1 t1
join table2 t2 on t1.ins1=t2.insco
union
select t2.insco from table1 t1
join table2 t2 on t1.ins2=t2.insco
union
select t2.insco from table1 t1
join table2 t2 on t1.ins3=t2.insco

As I mentioned, you need to normalise your data. This is every much overly simplified, due to the simplicity of your data, however, should get you on the right path:
CREATE TABLE dbo.YourTable1 (RowID int--,
--Other columns, but no ins1, 2, etc columns
);
INSERT INTO dbo.YourTable1 (RowID--,
--Other columns
)
VALUES(1),(2),(3);--Obviouslu, again you would have other columns, but not an ins columns
CREATE TABLE dbo.YourTable2 (Insc0 int);
INSERT INTO dbo.YourTable2 (Insc0)
VALUES(1),(2),(3),(4),(5);
CREATE TABLE dbo.LinkTable (RowID int,
Ins int);
INSERT INTO dbo.LinkTable (RowID,
Ins)
VALUES(1,1),(1,2),
(2,3),(2,4),
(3,5),(3,6);
GO
SELECT *
FROM dbo.YourTable1 YT1
JOIN dbo.LinkTable LT ON YT1.RowID = LT.RowID
JOIN dbo.YourTable2 YT2 ON LT.Ins = YT2.Insc0;
GO
--Clean up
DROP TABLE dbo.LinkTable;
DROP TABLE dbo.YourTable2;
DROP TABLE dbo.YourTable1;

Related

SQL Server: How to select missing rows in table from another table?

I have two tables like below:
table1:
StoreId SKU
------------
1 abc
2 abc
3 abc
1 xyz
4 xyz
table2:
StoreId
--------
1
2
3
4
5
I want to select missing storeid from the table1 which are in table 2. But condition is that in above example for SKU abc storeid 4 and 5 are missing and for sku xyz 2,3,5 are missing. So I want below table as output
SKU,ID
------
abc 4
abc 5
xyz 2
xyz 3
xyz 5
I am able to pull only the overall missing store which is 5 using below query.
SELECT
SKU, t2.StoreId
FROM
#table1 t1
FULL OUTER JOIN
#table2 t2 ON t1.StoreId = t2.StoreId
WHERE
t1.StoreId IS NULL
Below is test create and insert query.
Declare #table1 As table
(
StoreId varchar(4),
SKU varchar(5)
)
Declare #table2 As table
(
StoreId int
)
BEGIN
Insert Into #table1(SKU,StoreId) values('abc',1)
Insert Into #table1(SKU,StoreId) values('abc',2)
Insert Into #table1(SKU,StoreId) values('abc',3)
Insert Into #table1(SKU,StoreId) values('xyz',1)
Insert Into #table1(SKU,StoreId) values('xyz',4)
Insert Into #table2(StoreId) values(1)
Insert Into #table2(StoreId) values(2)
Insert Into #table2(StoreId) values(3)
Insert Into #table2(StoreId) values(4)
Insert Into #table2(StoreId) values(5)
END
Thank you
You need to get a list of all skus and tables, and then show only rows which do not appear in table1:
select SKU, StoreID
from #table2 t2
cross join (select distinct sku from #table1) t1
where not exists (select 1 from #table1 table1
where table1.SKU = t1.SKU
and table1.StoreId = t2.StoreId)
Here is an alternative solution with the same result.
Syntax is very similar to the answer from #BeanFrog:
SELECT
t3.SKU, t2.StoreID
FROM
#table2 t2
CROSS JOIN
(SELECT distinct SKU
FROM #table1) t3
LEFT JOIN
#table1 t1
ON
t1.SKU = t3.SKU
and t1.StoreId = t2.StoreId
WHERE
t1.sku is null

SQL Server : how to check if a row exist in other tables

I would like to ask for help if how can I write a T-SQL query that checks if a row exists in other tables and insert the data in a temporary table.
For example, I have 5 tables main1, table2, table3, table4 and table5. Each table has a product_id column.
I need main1.product_id (values A000 to A010) to check if they exist in table2, table3, table4 and table5.
If it is found in table2, the value "A000" will be inserted into a temporary table. If it is not found, it will check in table3; again if not found, it will check in table4.
Then main1.product_id value "A001" will be checked. If A001 is found in table2 it won't be checked in table3 and table4 anymore, it will be written into the temp table and next value is to be checked from main1 table, and so on,...
Thanks so much
Looks like you're looking for something like this:
insert into #tmp
select product_id
from main1 m
where
(
exists (select 1 from table2 t where t.product_id = m.product_id)
or exists (select 1 from table3 t where t.product_id = m.product_id)
or exists (select 1 from table4 t where t.product_id = m.product_id)
or exists (select 1 from table5 t where t.product_id = m.product_id)
)
This will check each of the tables, and if the row is found, inserts it into #tmp
Or, alternatively, you could just use UNION ALL like in
Insert into #tmp
Select product_id from main1 where exists
(select 1 from (
select product_id p from table2 union all
select product_id from table3 union all
select product_id from table4 union all
select product_id from table5
) all where p=product_id )

Merging two columns with values from another table

I have similar table
How can i merge these two tables ? There are other columns, but these are the same.
How can i fill Table1 with values of Table2 or merge these tables ?
In Table2 is only 1 customer.
So the result table will have all customers with their values (Table1 will have Customer4 with Sales 50).
Thank you.
To update the table do
update t1
set t1.sales = t2.sales
from table1 t1
join table2 t2 on t1.customername = t2.customername
and as a select use
select t1.customername,
coalesce(t1.sales, t2.sales) as sales,
t1.date,
t1.variable1
from table1 t1
left join table2 t2 on t1.customername = t2.customername

SQL Server stored procedure select, exists, multiple tables

Any method to do this?
Table1
1
2
3
4
5
Table2
3 (with the condition)
4 (without the condition)
I want to:
Select all records from Table1 if it exists in Table 2, where...(condition)
Select all records from Table1 if it not exists in Table2
Combine both select results. Sort all results with their created date.
For example, the result should be:
Result
1
2
3
5
Hopefully this can help.
SELECT t1.* from table1 t1
JOIN table2 t2
ON t1.ID = t2.ID
UNION ALL
SELECT t1.* from table1 t1 where ID in
(
SELECT t2.ID from table1 t1 except Select t2.ID from table2 t2
)
ORDER BY t1.CreatedDate
You can achieve this by doing:
SELECT t1.id
FROM Table1 t1
LEFT JOIN Table2 t2 on t1.id = t2.id
WHERE condition OR t2.id IS NULL
ORDER BY t1.CreatedDate;
See fiddle (I assumed condition to be t2.id!=4, but it can be anything else depending on other data in your tables).
There could be multiple solution.
One way
we can get the result set using two different queries and at last combine both of the result-set using UNION
Another way,
First statement is saying that get all the result set from TABLE1 if it exists in TABLE2 as well with some criteria (condition in where clause)
means using INNER JOIN we can achieve this
Second statement is saying get all the result set from TABLE1 which are not present in TABLE2
means along with INNER JOIN ed query also include the TABLE1's data if not present in TABLE2
here we can take the help of LEFT OUTER JOIN (taking TABLE1 on the left side)
Assumption: (condition: t1.Id != 4)
Let's try to understand the query using both of the above mentioned ways
---- -- --Step1 Create table and insert records
---- create table1 with Id int identity columsn
--CREATE TABLE Table1 (Id INT IDENTITY(1,1), CreatedDate smalldatetime default(getdate()));
--go
---- insert 1st 5 integers into Table1
--INSERT INTO Table1 DEFAULT VALUES
--go 5
---- create Table2 with Id int column
--CREATE TABLE Table2 (Id INT , CreatedDate smalldatetime default(getdate()));
--go
---- insert records 3,5 into Table2
--INSERT INTO Table2(Id) VALUES (3), (4);
-- -- -- Solution: one way
; WITH cteMyFirstResult AS
(
-- 2.1. Select all records from Table1 if it exists in Table 2, where...(condition)
SELECT
Id, CreatedDate
FROM Table1 AS t1
WHERE t1.Id IN (SELECT Id FROM Table2 AS t2)
AND t1.Id != 4 -- assumption it can be any condition
),cteMySecondResult AS (
-- 2.2. Select all records from Table1 if it not exists in Table2
SELECT
Id, CreatedDate
FROM Table1 AS t1 WHERE t1.Id NOT IN (SELECT Id FROM Table2 AS t2)
)
-- 2.3. Combine both select results. Sort all results with their created date.
SELECT
Id, CreatedDate
FROM cteMyFirstResult
UNION
SELECT
Id, CreatedDate
FROM cteMySecondResult
ORDER BY CreatedDate;
-- -- Solution: Another way (with bug)
SELECT t1.Id, t1.CreatedDate
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 on t1.id = t2.id
WHERE t1.Id != 4
Order by T1.CreatedDate;
-- in this query we are using the criteria after doing the join operation.
-- thus after filtering out the result set based on JOIN Condition this condition will get applied
-- and if there is any null record in the Table1 for column Id (used in join) will not come in the final result-set
-- to avoid this we can include NULL check along with our criteria
-- -- Solution: Another way
SELECT t1.Id, t1.CreatedDate
FROM Table1 AS t1
LEFT JOIN Table2 AS t2 on t1.id = t2.id
WHERE ( t1.Id != 4 ) OR t1.Id IS NULL -- include all your criteria within small-barcket)
Order by T1.CreatedDate;
Thanks for all responses.
I come out with the answer I want:
SELECT *
FROM Table1 t1
WHERE NOT EXISTS(SELECT 1 FROM Table2 t2
WHERE t1.ID = t2.ID
AND t2.CIF_KEY = #CifKey
AND t2.STATUS <> ''3'')
AND (condition in where clause)

Select matching records from Table 1 if Table 2 has records, otherwise select all from Table 1

Situation:
I have two tables
Table 1 always has records
Table 2 is the result of a select statement and may or may not have records
Desired Results:
If Table 2 has ANY records, I want only matching records from Table 1. Otherwise, I want all records from Table 1.
I realize I can do this:
DECLARE #count int
SELECT #count=COUNT(*) FROM Table2
IF #count>0
SELECT t1.* FROM Table1 t1 INNER JOIN Table2 t2 ON t1.id=t2.id
ELSE
SELECT * FROM Table1
However, I am trying to avoid IF statements if possible.
Is that even possible?
select t1.*
from Table1 t1
left join
Table2 t2
on t1.id = t2.id
where t2.id is not null -- Match found
or not exists -- Or Table2 is empty
(
select *
from Table2
)

Resources