Update Query in SQL Server via JOINS - sql-server-2008

I have 2 tables as mentioned below
create table #temp(id int, userid int,age int)
insert into #temp values (1,1,1)
insert into #temp values(2,1,2)
insert into #temp values(3,1,3)
create table #tempMOCK(id int, userid int,age int)
insert into #tempMOCK values (6,1,7)
insert into #tempMOCK values (7,1,9)
I want to update the first 2 rows of Mock table on #temp table. I am expecting that age of rowids 2 & 3 should become 7 & 9. I'm using this query but somehow it doesn't work.
UPDATE t1
SET t1.age = t2.age
FROM #temp t1
INNER JOIN #tempMOCK t2 ON t1.userid = t2.userid where t1.id in (1,2)

Since the user id is the same in all rows, you get the same value for the age.
This can be solved using a CTE, like this:
;with cte as
(
select id, userid, age, ROW_NUMBER() OVER(order by id) rn
FROM #tempMock
)
UPDATE t1
SET t1.age = t2.age
FROM #temp t1
INNER JOIN cte t2 ON t1.userid = t2.userid and t1.id = t2.rn+1;
see fiddle here

you can try following query for this:
UPDATE #temp1 set age=(Select t2.age from #tempMOCK t2
where t2.userid=#temp1.userid) where id in (1,2)
Hope it helps

Related

SQL code to select records where field_A matches the field_A value of a certain field_B value

I have this table
ID Email
aa aa#gmail.com
aa aa#yahoo.com
bb bb#gmail.com
cc cc#hotmail.com
Using SQL code, I want to select all records that has the same ID as the ID of email aa#gmail.com. So it will return:
aa aa#gmail.com
aa aa#yahoo.com
I know that we can select records where field_A is a certain value like this:
SELECT * FROM tablename WHERE ID="aa"
How can I modify this code to achieve the desired results?
You can use a subquery:
SELECT t.*
FROM tablename t
WHERE t.ID = (SELECT t2.id
FROM tablename t2
WHERE t2.email = 'aa#gmail.com'
);
select * from tablename where id in (
SELECT ID AS count FROM tablename GROUP BY ID HAVING COUNT(ID) > 1
)
Using JOIN the same table ON ID, the result is possible:
SELECT T1.ID, T2.Email
FROM TableName T1
JOIN TableName T2 ON T2.ID = T1.ID
WHERE T1.Email = 'aa#gmail.com'
Demo on db<>fiddle
You can use SUBSTRING_INDEX
SELECT * FROM tablename WHERE ID=SUBSTRING_INDEX(`Email`, '#', 1) and Email='aa#gmail.com'
Instead of hardcoding it should return values after evaluating
CREATE TABLE TestTable (ID VARCHAR(5), Email VARCHAR (20));
INSERT INTO TestTable (ID, Email) VALUES
('aa', 'aa#gmail.com'),
('aa', 'aa#yahoo.com'),
('bb', 'bb#gmail.com'),
SELECT *
FROM TestTable
WHERE ID IN
(
SELECT CASE WHEN ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID)>1 THEN ID END AS ID
FROM TestTable
)

How to DELETE the NEXT row values that is going to match the PREVIOUS row values base on a 2 column in MySQL

I need help and I want to know, if how can I delete the next row or column values that matches the previous row or column values on a MySQL table base from a 2 columns.
So, if the next row/column values/result contains the same values on the previous rows/columns values/result it will be deleted, but if the next column didn't match both of the previous column values/result, that row should not be deleted. What will be the right query for that condition?
I'm trying to make a select query first, to verify the data and this is my query for the select. Is my query right for the select?
SELECT current_row.row, current_row.id, current_row.column1,
current_row.column2, previous_row.row, previous_row.id,
previous_row.column1, previous_row.column2
FROM
(SELECT #rownum:=#rownum+1 row, a.*
FROM MyTable a, (SELECT #rownum:=0) r
ORDER BY unix_time, id
) as current_row
LEFT JOIN
(SELECT #rownum2:=#rownum2+1 row, a.*
FROM MyTable a, (SELECT #rownum2:=0) r
ORDER BY unix_time, id) as previous_row
ON (current_row.id = previous_row.id)
AND (current_row.column1 = previous_row.column1)
AND (current_row.column2 = previous_row.column2)
AND (current_row.row = previous_row.row - 1)
LIMIT 10;
Thank you very much in advance for any help!
Cheers!
We're trying to select data with assigned new virtual id for comparing, so ON clause should be t1.myid=t2.myid+1 and WHERE clause should filter col1 and col2 rows:
SET #id1:=0 , #id2:=0 ;
SELECT * FROM (
(SELECT *, #id1:=#id1+1 as myid from mytable ) as t1
LEFT JOIN
(SELECT *, #id2:=#id2+1 as myid from mytable ) as t2
ON t1.myid = t2.myid + 1
)
WHERE t1.col1= t2.col1 and t1.col2 = t2.col2
And for DELETE command, you should save results in temporary table and then delete rows where their id is stored in temp table:
SET #id1:=0 , #id2:=0 ;
CREATE TEMPORARY TABLE tbl_ids AS
SELECT t1.id FROM ( -- t1.id returns NEXT row
(SELECT *, #id1:=#id1+1 as myid from mytable ) as t1
LEFT JOIN
(SELECT *, #id2:=#id2+1 as myid from mytable ) as t2
ON t1.myid = t2.myid + 1 -- t1.myid > t2.myid
)
WHERE t1.col1= t2.col1 and t1.col2 = t2.col2 ;
DELETE FROM mytable WHERE id in (SELECT * FROM tbl_ids) ;

Creating a View that returns the first occurrence of a value

I'm trying to create a view that returns the first occurrence of a value.
I have two tables
First table:
sID | dt
12 | DateTimeValue1
12 | DateTimeValue2
second table:
S_ID
12
I want the view to join both tables and give me the first occurance of S_ID (in this case DateTimeValue1)
How can I accomplish this?
More Info:
in table 1 I have two columns sID and dt. Values for these columns look like this:
sID: 1 dt: 2014-06-12
sID: 1 dt: 2014-06-13
sID 1 dt: 2014-06-14 etc...
I want to join the two tables in my view so that
where S_ID matches sID it returns the first value (in this case 2014-06-12)
Sorry for any confusion!
Here's what I got so far:
This is what I got so far:
CREATE VIEW view_name AS
SELECT [S_ID]
FROM table1
LEFT JOIN table2
ON table1.[S_ID]=table2.sID;
You could do something like : http://sqlfiddle.com/#!3/66ee02/1
create view theview as
select
t1.s_id, min(dt) dt
from
table1 t1 inner join
table2 t2 on t1.s_id = t2.s_id
group by
t1.s_id
In MS SQL Server you can select the first row of table1 and join it with table2 in a view like this:
create view view_name
as
select table1.*,table2.*
from table2
inner join
(select top 1 *
from table1
order by table1.what_ever_field) as table1
on table2.id = table1.id
This works well if table2 has a foreign key to table1.
If they are independent tables with no foreign keys You can do this:
create view view_name
as
select table1.*,table2.*
from (select top 1 * from table2 order by table2.field1) as table2
,
(select top 1 * from table1 order by table1.field1) as table1
Please try :
select t1.sID,min(t1.dt) from first_table t1, second_table t2 where t1.sID=t2.sID group by t1.sID
I tried same with below code in sybase and it worked well.
create table #temp1
(sID int,dt date)
create table #temp2
(sID int)
insert into #temp1
select 12,getdate()
insert into #temp1
select 12,getdate()
insert into #temp1
select 12,getdate()
insert into #temp2
select 12
insert into #temp1
select 13,getdate()
insert into #temp2
select 13
insert into #temp1
select 14,getdate()
insert into #temp1
select 14,getdate()
insert into #temp2
select 14
select * from #temp1
select * from #temp2
select t1.sID,min(t1.dt) from first_table t1,
second_table t2
where t1.sID=t2.sID
group by t1.sID

Search for values in table1 that match values in table2 without joins (Sql Server 2008)

I ran into a situation where I have two tables that store employee information, Table1 are the employees and table2 are 3rd party temps. These tables use a different convention for the IDs (not something I have control over).
The problem is that oftentimes these 3rd party temps become employed and there is no link between these tables. When this happens, I need to make sure they don't exists in Table2 before I create them. Right now the I just want to identify matches on DOB & Last 4, although I'm probably going to add at least first name to the criteria but right now I'd like to start somewhere.
The columns although name differently are the same (DOB = Birth Date, Code = Last 4)
CREATE TABLE Table1
([Emp_ID] int, [DOB] date, [code] varchar(10))
;
INSERT INTO Table1
([Emp_ID], [DOB], [code])
VALUES
(55556, '1966-01-15', '5454'),
(55557, '1980-03-21', '6868'),
(55558, '1985-04-26', '7979'),
(55559, '1990-10-17', '1212'),
(55560, '1992-12-30', '6767')
;
CREATE TABLE Table2
([USer_ID] int, [Birth_Date] date, [last4] varchar(10))
;
INSERT INTO Table2
([User_ID], [Birth_Date], [last4])
VALUES
(22223, '1966-01-15', '5454'),
(22224, '1980-03-21', '6868'),
(22225, '1975-07-19', '4545'),
(22226, '1988-05-24', '3434')
;
Here is what I came up with, It seems to work but I need to return the user_id from table2 that is producing this match?
SELECT *
FROM table1 t1
WHERE EXISTS (SELECT 1 FROM table2 t2 WHERE t1.DOB = t2.Birth_date)
AND EXISTS (SELECT 1 FROM table2 t2 WHERE t1.code = t2.last4)
Thanks!
Try this
Without JOINS:
SELECT t1.*,
(SELECT user_id FROM table2 t2
WHERE t1.DOB = t2.Birth_date and t1.code = t2.last4) user_id
FROM table1 t1
WHERE EXISTS (SELECT 1 FROM table2 t2
WHERE t1.DOB = t2.Birth_date and t1.code = t2.last4)
With JOINS
SELECT t1.*, t2.user_id
FROM table1 t1
inner join table2 t2 on t1.DOB = t2.Birth_date and t1.code = t2.last4
SQL DEMO

Copy rows from one table to another, ignoring duplicates

Im trying to copy row from table to another using 2 coluom only as the tow table schema is not identical ,
am getting this error
Operand should contain 1 column(s)
Any tips whats wrong with my statement ?
Insert table1 ( screenname,list_id )
Select screenname,list_id
From table2 As T1
Where Not Exists (
Select 1
From table1 As T2
Where
(T2.screenname = T1.screenname,T2.list_id = T1.list_id)
)
try to change where condition from (T2.screenname = T1.screenname,T2.list_id = T1.list_id) to (T2.screenname = T1.screenname AND T2.list_id = T1.list_id)
(note AND keyword instead of comma)
Did you try INSERT INTO...ON DUPLICATE KEY syntax?
See MySQL manual here
You can create a unique index in table1 on the columns screenname and list_id
Then use the following statement
Insert ignore into table1 ( screenname,list_id )
Select screenname,list_id
From table2 As T1
Also try this query -
INSERT INTO table1 (screenname, list_id)
SELECT screenname, list_id FROM table2 t2
LEFT JOIN table1 t1
ON t1.screenname = t2.screenname AND t1.list_id = t2.list_id
WHERE
t1.screenname IS NULL AND t1.list_id IS NULL;
Use simple INSERT IGNORE
INSERT table1 (screenname, list_id) SELECT screenname, list_id FROM table2