I have a table with two columns. I want to compare each row of the first column with all rows in the second column. If matched I need to insert yes in the 3rd column, if not I need to insert no.
First second
A B
C D
E A
X c
Output should be
First second yesOrno
A B yes
C D yes
E A NO
X c NO
Use an EXISTS with the same table.
UPDATE T1 SET
ThirdColumn = CASE WHEN EXISTS (
SELECT
'a SecondColumn match exists'
FROM
YourTable AS T2
WHERE
T1.FirstColumn = T2.SecondColumn) THEN 'Yes' ELSE 'No' END
FROM
YourTable AS T1
SELECT
First, Second,
CASE WHEN EXISTS (
SELECT * FROM Table t2
WHERE t2.Second = t1.First)
THEN 'Yes' ELSE 'No' END AS YesOrNo
FROM
Table t1
you can get it by self join as below
select T1.First,T1.second,(case when T2.second is null then 'no' else 'yes' end) as yesOrno from T as T1 left join T as T2
on T1.First=t2.second
check sql fiddle : SQL Fiddle
You can do it like this:
declare #t table (
C1 char(1),
C2 char(1)
)
insert #t
values ('A','B'),
('C','D'),
('E','A'),
('X','C')
select t1.C1,t1.C2, case when t2.C2 is null then 'No' else 'Yes' end YesOrNo
from #t t1 left join #t t2
on t1.C1 = t2.C2
There are many different ways of writing this basic query.
Related
I have this tables:
I need to update sum_ok and avg_ok considering values from table 1 like this:
I have this code SQL, but don't work fine:
update
t2
set sum_ok = sum(case when t2.[status]='OK' then 1 else 0 end )
,avg_ok = avg(case when t2[status]='OK' then status end )
from t1
inner join t2
on t1.A = t2.A --and t1.C = t2.C
where C is not null
group by A, C
Thanks!!
One option is to compute your "sum_ok" and "avg_ok" values separately, then apply the UPDATE statement while joining your "t2" table and your computed values:
WITH cte AS (
SELECT A,
C,
SUM(CASE WHEN [status] = 'ok' THEN 1 END) AS sum_ok,
AVG(CAST ([value] AS FLOAT)) AS avg_ok
FROM t1
GROUP BY A, C
)
UPDATE t2
SET t2.sum_ok = cte.sum_ok,
t2.avg_ok = cte.avg_ok
FROM t2
INNER JOIN cte
ON t2.A = cte.A AND t2.C = cte.C;
Check the demo here.
Note: in your query you're trying to access the "t2.status" field, whereas "t2" table doesn't have it.
I have table A and table B . I have to compare this tables records and insert data to table C using SQL Server procedure in below format
table A
name
A
B
C
D
E
F
G
table B
name
A
B
Q
C
D
F
G
table c should be like below. it has an extra field 'status' to mention record is added or removed.
name status
A
B
Q newly added
C
D
E removed
F
G
I know we can compare 2 tables and find added or removed records using EXCEPT and UNION operations. But in this case, I have to integrate that records with unchanged records and should place that added or removed records in correct position.
You can do this with a full join and conditional logic:
select
coalesce(a.name, b.name) name,
case
when a.name is null then 'newly added'
when b.name is null then 'removed'
end status
from tablea a
full join tableb b on b.name = a.name
order by name
Demo on DB Fiddle:
name | status
:--- | :----------
A | null
B | null
C | null
D | null
E | removed
F | null
G | null
Q | newly added
Depending on which order do you want to accomplish at the end you can use this:
select name, max(status), descr from(
select
coalesce(a.col, b.col) name,
coalesce(a.descr, b.descr) descr,
case
when a.col is null then 'newly added'
when b.col is null then 'removed'
end status
, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) rn
from a a
left join b b on b.col = a.col
union
select
coalesce(a.col, b.col) name,
coalesce(a.descr, b.descr) descr,
case
when a.col is null then 'newly added'
when b.col is null then 'removed'
end status
, ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) rn
from b b
left join a a on b.col = a.col) A
group by name, descr
order by max(rn);
And then if you want to order by how it is in table a then in first select select from b left join a and in your second select from a left join b and if you want to oder by how it is in table b then in first select select from a left join b and in your second select from b left join a.
Here is a demo with the last requested samle data.
You could try using a some union and left join
select A.name, case when is null t1.name then 'newly addedd' end
from A
left JOIN (
select A.name from A
union B.name from B
) t1
union
select B.name, case when is null t1.name then 'delete' end
from B
left JOIN (
select A.name from A
union B.name from B
) t1
You should use FULL OUTER JOIN.
DECLARE #table1 TABLE(
[name] char(1)
)
DECLARE #table2 TABLE(
[name] char(1)
)
INSERT INTO #table1 VALUES ('A'),('B'),('C'),('D'),('E'),('F'),('G')
INSERT INTO #table2 VALUES ('A'),('B'),('Q'),('C'),('D'),('F'),('G')
SELECT
IIF(T1.name IS NULL,T2.name,T1.name) as 'Name',
CASE WHEN T1.name IS NULL THEN 'newly added' WHEN T2.name IS NULL THEN 'removed' ELSE '' END as 'Status'
FROM #table1 T1
FULL OUTER JOIN #table2 T2 ON T1.name = T2.name
There ise one more possible method:
DECLARE #table1 TABLE(
[name] char(1)
)
DECLARE #table2 TABLE(
[name] char(1)
)
INSERT INTO #table1 VALUES ('A'),('B'),('C'),('D'),('E'),('F'),('G')
INSERT INTO #table2 VALUES ('A'),('B'),('Q'),('C'),('D'),('F'),('G')
SELECT
T1.name as 'Full_List',
IIF(T2.name IS NOT NULL,'','removed') as 'Status'
FROM #table1 T1
LEFT OUTER JOIN #table2 T2 ON T1.name = T2.name
UNION ALL
SELECT
T2.name,
IIF(T1.name IS NULL,'Added','')
FROM #table2 T2
LEFT OUTER JOIN #table1 T1 ON T1.name = T2.name
WHERE T1.name IS NULL
please try with below query (SQL FIDDLE):
CREATE PROCEDURE update_records
AS
BEGIN
INSERT INTO C(name, status)
SELECT AB.name, AB.status FROM(
SELECT (case when A.name is null then B.name else A.name end) as name,
(CASE
WHEN A.name is null THEN 'newly added'
WHEN B.name is null THEN 'removed'
END) AS status
FROM A
FULL JOIN B on B.name = A.name
) as AB
ORDER by AB.name
END
I work with student data and have two tables with the same structure but different data sets. I would like to add a new column with a record of '0' or '1' to determine whether or not the student appears in the other table. Example:
Table 1:
s_id s_year s_term s_crs NewColumn(was student enrolled in 2016?)
123456 2017 Fall Math 1010 1
654321 2017 Fall Eng 1010 0
Table 2:
s_id s_year s_term s_crs
123456 2016 Fall Math 2010
432516 2016 Fall Eng 2010
How would you go about doing this?
SELECT s_id, s_year, s_term, s_crs
(CASE
WHEN S_ID IN (select s_id from table2)
THEN '1'
or something of that nature? I am unsure how to write this with a join
You could left join with the second table, and see if it the resulting column is not null:
SELECT t1.s_id, t1.s_year, t1.s_term, t1.s_crs,
CASE WHEN t2.s_id IS NOT NULL THEN 1 ELSE 0 END AS newcolum
FROM table1 t1
LEFT JOIN table2 t2 ON t1.s_id = t2.s_id
assuming table 1 is the result ... using subquery solely based on the s_id and s_year... if there is another requirement please update OP.
SELECT
s_id,
s_year,
s_term,
s_crs,
ISNULL((SELECT
1
FROM table2 t2
WHERE t2.s_id = t1.s_id
AND t2.s_year = 2016), 0) [NewCol 2016]
FROM table1 t1
Assuming the s_id is a common identificator
SELECT t1.s_id, t1.s_year, t1.s_term, t1.s_crs, 1 as NewColumn
FROM table1 t1
WHERE EXISTS (SELECT 1 FROM Table2 t2 WHERE t1.s_id = t2.s_id)
UNION
SELECT t1.s_id, t1.s_year, t1.s_term, t1.s_crs, 0 as NewColumn
FROM table1 t1
WHERE NOT EXISTS (SELECT 1 FROM Table2 t2 WHERE t1.s_id = t2.s_id)
You can do this
ALTER TABLE Table1 ADD NewColumn BIT NOT NULL DEFAULT (0)
At this point all your items in the Table1 will be 0, now you just update the needed items with 1
UPDATE Table1
SET NewColumn = 1
WHERE ID IN (SELECT ID FROM Table2)
You can use Left join
SELECT t1.s_id, t1.s_year, t1.s_term, t1.s_crs,
CASE WHEN t2.s_Year = '2016' THEN 1 ELSE 0 END AS [NewColumn(was student enrolled in 2016?)]
FROM table1 t1
LEFT JOIN table2 t2 ON t1.s_id = t2.s_id
create table #tbl1
(
s_id int,
s_year varchar(4),
s_term varchar(4),
s_crs varchar (10)
)
insert into #tbl1 values(123456,'2017','Fall','Math 1010')
insert into #tbl1 values(654321,'2017','Fall','Eng 1010')
create table #tbl2
(
s_id int,
s_year varchar(4),
s_term varchar(4),
s_crs varchar (10)
)
insert into #tbl2 values(123456,'2016','Fall','Math 2010');
insert into #tbl2 values(432516,'2016','Fall','Eng 2010')
select a.s_id,a.s_year,a.s_term,a.s_crs,case when b.s_id is null then '0' else '1' end as NewColumn
from #tbl1 a left outer join #tbl2 b on a.s_id = b.s_id
drop table #tbl1
drop table #tbl2
I am having Table1 with Column A and Table2 with Column B.
When I use join, (Table1.A = Table2.B) I need to create a temp column 'Flag' and set Flag value as '1' for matching records and for remaining records(Table1.A != Table2.B) should have flag value '0'.
Result set should have column from both the table and flag value.
Thanks in advance.
You can use LEFT JOIN with ISNULL as below:
SELECT *,CASE WHEN t2.B IS NULL THEN 0 ELSE 1 END Flag
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.A=t2.B
For displaying unmatched values also from right table
SELECT *,CASE WHEN t1.A IS NULL OR t2.B IS NULL THEN 0 ELSE 1 END Flag
FROM Table1 t1
FULL OUTER JOIN Table2 t2 ON t1.A=t2.B
Try with FULL OUTER JOIN .
SELECT *,CASE WHEN t1.A = t2.B THEN 1 ELSE 0 END Flag
FROM Table1 t1
FULL OUTER JOIN Table2 t2 ON t1.A=t2.B
Check below example:
DECLARE #tblA AS TABLE
(
ID INT,
A VARCHAR(50)
)
DECLARE #tblB AS TABLE
(
ID INT,
B VARCHAR(50)
)
INSERT INTO #tblA VALUES(1,'AA'),
(2,'CCC'),
(3,'DDD'),
(4,'FFF')
INSERT INTO #tblB VALUES(1,'AA'),
(2,'BBB'),
(3,'DDD'),
(4,'KKK')
SELECT
A.A,
B.B,
CASE ISNULL(B.B,'') WHEN '' THEN 0 ELSE 1 END AS Match
FROM #tblA A
LEFT JOIN #tblB B ON A.A=B.B
I have 2 tables... table1 and table2.
I want to display all serial numbers from table1
table2 has also has serial numbers in it
I would like to compare the serial numbers in table1 with table2
I would then like to display all the serial numbers in table1 and have a second column with a yes if the serial number was in table1 or a no if it wasn't
Is this possible to do with a sql statement or do I have to build a seperate table? i'm running sql-server.
If serial numbers in each table are unique then you could use:
SELECT Table1.SerialNumber,
CASE WHEN Table2.SerialNumber IS NULL THEN 'No' ELSE 'Yes' END AS [IsInTable2]
FROM Table1.SerialNumber
LEFT JOIN Table2
ON Table2.SerialNumber = Table1.SerialNumber
If there are Duplicates in one or both tables then either of the following will work:
SELECT DISTINCT
Table1.SerialNumber,
COALESCE([IsInTable2], 'No') [IsInTable2]
FROM Table1.SerialNumber
OUTER APPLY
( SELECT TOP 1 'Yes' [IsInTable2]
FROM Table2
WHERE Table2.SerialNumber = Table1.SerialNumber
) Table2
SELECT DISTINCT
Table1.SerialNumber,
CASE WHEN Table2.SerialNumber IS NULL THEN 'No' ELSE 'Yes' END [IsInTable2]
FROM Table1.SerialNumber
LEFT JOIN
( SELECT DISTINCT SerialNumber
FROM Table2
) Table2
ON Table2.SerialNumber = Table1.SerialNumber
If we assume that the serial numbers are unique in each table then you can do an outer join. Using a LEFT OUTER JOIN will grab you all rows from the left side and optionally grab you any matching rows on the right side. Then you can do a comparison to see if a matching row was found in table2.
SELECT t1.serial, CASE WHEN t2.serial IS NULL THEN 'No' ELSE 'Yes' END
FROM table1 t1
LEFT OUTER JOIN table2 t2 ON t1.serial = t2.serial;
Try this
SELECT t1.serialnumber as serialnumber, Case
WHEN t1.serialnumber = t2.serialnumber then 'YES' else 'NO' END
FROM table1 t1
LEFT JOIN table2 t2 with (nolock) on t1.serialnumber = t2.serialnumber;
Hopefully that should work