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)
Related
I have two tables t1 and t2.
t1 having 10k records and t2 having 2k records. The 2k records of t2 is present in t1.
I wanted the 8k different records from t1 which is not present in t2.
I'm doing this as below:
select id, second_telphon from t1
except
select id, second_telphon from t2
However, I'm still getting all the 10k records. Is "except" keyword not working?
how can I achieve this?
you can perform a Join to get the unique data from the tables .
like the tables t1 & t2 both you cna perform left or right join .
example:
SELECT T1.*
FROM T1
WHERE NOT EXISTS(SELECT NULL
FROM T2
WHERE T1.ID = T2.ID
AND T1.Date = T2.Date
AND T1.Hour = T2.Hour)
OR .
SELECT T1.*
FROM T1
LEFT JOIN T2
ON T1.ID = T2.ID
AND T1.Date = T2.Date
AND T1.Hour = T2.Hour
WHERE T2.ID IS NULL
Try this:
SELECT *
FROM T1
WHERE NOT EXISTS(SELECT id,second_telphon FROM t2)
If ID is a unique value, Try this also:
SELECT *
FROM T1
WHERE ID NOT IN(SELECT ID FROM t2)
You could try a union, followed by an aggregation to restrict to those records in the first table which were not duplicated by the second table:
SELECT id, second_telphon
FROM
(
SELECT id, second_telphon FROM t1
UNION ALL
SELECT id, second_telphon FROM t2
) t
GROUP BY id, second_telphon
HAVING COUNT(*) = 1;
If a record, being defined as an id, second_telphon pair, has a record count of only one after the union, it implies that this record was unique to the first table.
Just do left join
select t1.id,t1.second_telphon from t1
left join t2 on
t1.id = t2.id
and t1.second_telphon =t2.second_telphon
where t2.id is null
Perhaps quite a simple question, that seems to have a rather complicated answer that I have not been able to dig out.
Im using an SQL-server 2012.
I have these two statements, that selects all my data based on a parameter, and then also selects up to five rows of data (which means no joins) from another table based on the IDs gotten from the first select.
SELECT * FROM TBL1 WHERE XXX
SELECT * FROM TBL2
WHERE TBL1_ID IN (SELECT ID FROM TBL1 WHERE XXX)
It seems very redundant to me, that I basicly have to repeat my TBL1 select in my TBL2, and instead I would like to know if I can select from TBL2 using the ID's from the * data I got from TBL1.
I am fully aware that this will most likely result in two resultsets that dont necessarily correlate, but I can generally use PHP array-manipulation to fix this so its not that big of a deal.
You also use EXISTS
SELECT * FROM TBL2
WHERE EXISTS (SELECT 1 FROM TBL1 WHERE TBL1.ID = TBL2.TBL1_ID AND XXX)
Using IN:
Declare #T1 table (ID INT , Value VARCHAR(50) );
Declare #T2 table (ID INT);
INSERT INTO #T1 Values (1,'First') , (2,'Second');
INSERT INTO #T2 Values (1),(3);
SELECT * FROM #T1 WHERE ID IN (SELECT ID FROM #T2);
Resault :
ID Value
----------- ------------------------------------------------------------------------------
1 First
Using INNER JOIN :
SELECT T1.ID , T1.Value FROM #T1 T1 INNER JOIN #T2 T2 ON T1.ID = T2.ID;
Resault:
ID Value
----------- ------------------------------------------------------------------------------
1 First
Using LEFT JOIN :
SELECT T1.ID , T1.Value FROM #T1 T1 LEFT JOIN #T2 T2 ON T1.ID = T2.ID
WHERE T2.ID IS NOT NULL;
Resault :
ID Value
----------- -------------------------------------------------------------------------------
1 First
[Below are two tables Table1 and Table2][1]
Table1:Column names id,name
Table2:Column names id,name
After the swap ,the name column data of Table1 will reflect in Table2 and name of Table2 will reflect in Table1.
I tried to resolve the issue using below query:
update table1 t set t.name=replace(t.name,(select name from T1 where T1.id=t.id),(select name from T2 where T2.id = t.id));
update table2 t set t.name=replace(t.name,(select name from T2 where T2.id=t.id),(select name from T1 where T1.id = t.id));
But,it is not giving correct result.
You can't do this in a single pass, as you are overwriting the values you want to move in the next step. Here's a solution using a temporary table:
SELECT * INTO #temp FROM table1;
UPDATE t1 SET name = t2.name FROM table1 t1 INNER JOIN table2 t2 ON t2.id = t1.id;
UPDATE t2 SET name = t1.name FROM #temp t1 INNER JOIN table2 t2 ON t2.id = t1.id;
DROP TABLE #temp;
A little modification in your query and it worked.
create table temp1 as select * from table1;
update table1 set name = (select name from table2 where table2.id = table1.id);
update table2 set name = (select name from temp1 where temp1.id = table2.id);
Thanks,
Vinita Singh
I am going to do the following in a STORED PROCEDUREin T-SQL.
Table1 consists of some rows that are arbitrary. Table2 consists of more rows than Table1, but those that exists are the same, except for one column which holds a date.
If a row in Table1 exists in Table2, I want to update the date column for Table2.
If a row in Table2 does not exist in Table1, I want to update the date column for Table2 as well.
I cannot for the life of me figure out the syntax to make this happen, as this stored procedure will not take in any parameters or output any parameters.
First of all you should get diff of tables. Check following:
set nocount on
declare #t1 table (id int, datecolumn datetime)
declare #t2 table (id int, datecolumn datetime, fk_on_t1 int)
declare #diff table(t1_id int, t2_id int)
insert into #diff(t1_id,t2_id)
select
t1.Id
,t2.ID
from #t1 t1
full join #t2 t2 on t1.id = t2.fk_on_t1
Now you can understand what rows exists one or another tables. You can use query like this to update your date column for your case:
update t2
set datecolumn = getdate()
from #t2 t2
inner join #diff d on d.t2_id = t2.ID
where d.t2_id is not null
Commonly, you can make just one query instead of mine two. Check this:
update t1
set datecolumn = getdate()
from #t1 t1
full join #t2 t2 on t1.id = t2.fk_on_t1
where t2.ID is not null
update table1
set table1.date = insull(table2.date, getdate())
from table1
left jion table2
on table2.ID = table1.ID
try this
UPDATE A
SET A.datecol= CASE
WHEN EXISTS (SELECT 1
FROM Table1 B
WHERE B.cola = A.cola) THEN c.Datecol
ELSE getdate()
END
FROM Table2 A
JOIN Table1 C
ON a.cola = c.cola
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
)