Insert data from Table1 to Table2 in SQL - sql-server

I have two tables, table1 has 2 columns and table2 has 3 columns.
I would like to insert values of table1 col1 and table1 col2 into `table2 of one column.
Here is data from table1:
╔════════╦════════╗
║ Col1 ║ Col2 ║
╠════════╬════════╣
║ Value1 ║ Value2 ║
╚════════╩════════╝
Insert that into a table2 row: like
╔════════╦
║ Value1 ║
╠════════╣
║ Value2 ║
╚════════╝
How to do this with SQL?

If you want to copy each in a different row use:
INSERT INTO table2 (col1, col2)
SELECT col1, col2 FROM table1;
Or One by One
INSERT INTO table2 (col1)
SELECT col1 FROM table1;
INSERT INTO table2 (col2)
SELECT col2 FROM table1;
If you want to concatenate in the same row use
INSERT INTO table2 (col3)
SELECT col1 + col2 FROM table1;
OR
INSERT INTO table2 (col3)
SELECT col1 || col2 FROM table1;
http://www.w3schools.com/sql/sql_insert_into_select.asp

Related

SQL Server append table to an existing table

I need to append rows from one table to an existing table. I am thinking something like following but this gives an error
select *
into table1
from (select *
from table1
union
select *
from table2) as tmp
Is there a way to use ALTER TABLE or UPDATE with UNION?
i will assume the below scenario ,
1- you need to insert in table1 all data from table 2
use this one
INSERT INTO TABLE1 (Col1, Col2)
SELECT Col1, COl2 FROM Table2
2- you have 2 tables , table 1 and need to insert in table 3
INSERT INTO TABLE3 (Col1, Col2)
SELECT Col1, COl2 FROM Table1
Union all --to remove duplication in data
SELECT Col1, COl2 FROM Table2
Just do a direct insert to Table1 from Table2
INSERT INTO TABLE1 (Col1, Col2)
SELECT
Col1, COl2
FROM
Table2
Use this query:
-- merge table1 and table2 data in temp table
SELECT * INTO #Temp
FROM
(
SELECT *
FROM table1
UNION
SELECT *
FROM table2
)
-- empty table1 and delete existing data
TRUNCATE TABLE table1
-- insert all merged data in table 1
INSERT INTO table1
SELECT *
FROM #Temp
You can remove duplicate rows with using UNION ALL instead of UNION

SQL Server - Delete Duplicate Rows that based on different rows from another field

i have column and rows in my table as below
col0 col1 col2 col3 col4
----------------------------
1 A 1 100 AA
2 B 2 200 BB
3 B 1 100 AA
4 A 2 200 BB
i want the final result is
col0 col1 col2 col3 col4
----------------------------
1 A 1 100 AA
2 B 2 200 BB
OR
col0 col1 col2 col3 col4
----------------------------
3 B 1 100 AA
4 A 2 200 BB
i want to delete first and second rows OR third and fourth rows but based on col1, as you can see, their's not same with each other rows except with the col0, because the col0 is primary key. how should i do with sql server express 2012?
Here is an option for deleting the first pair of duplicate records. You can assign a row number based on a partition of the four data columns. Do this in a CTE, and then delete all records from that CTE where the row number is 1.
WITH cte AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY col2, col3, col4 ORDER BY col0) rn
FROM yourTable
)
DELETE
FROM cte
WHERE rn = 1
Follow the link below for a demo showing that the logic of my CTE is correct.
Demo
You can use this
DELETE FROM yourTable
WHERE col0 NOT IN ( SELECT MIN(col0) FROM yourTable GROUP BY col1)

Convert column to rows in SQL Server

I have a scenario where I need to convert column to rows. I have two tables table1 and table2 with the following structure
Table1:
Col11 Col12 Col13
-------------------------
200 text 55
Table2:
Col1 Col2
--------------------
Col11
Col12
Col13
In need the following result from the above two tables
Col1 Col2
--------------------
Col11 200
Col12 text
Col13 55
Is it possible to do this by using temp tables ?
You can do it using UNION ALL:
SELECT 'Col1' AS Col1, Col1 AS Col2
FROM mytable
UNION ALL
SELECT 'Col2', Col2
FROM mytable
UNION ALL
SELECT 'Col3', Col3
FROM mytable
Table2 doesn't seem to play any role in producing the required result set. So it is left out in the above query.
you can use cross apply or UNPIVOT to get
select
coll,colvalue
from PivotColToRow
cross apply
(
select 'col1', col1 union all
select 'col2', col2 union all
select 'col3', col3
) c (Coll, colvalue);
Using UNPIVOT
select col,colvalue
from PivotColToRow
unpivot
(
colvalue
for col in (col1, col2, col3)
) unpiv;
try this

Get values NOT IN Table1 when join with Table2

I have two tables as below:
Table1:
Col1 Col2
834 2
834 3
834 5
877 1
877 2
877 5
900 10
900 2
900 3
Table2:
Col3
1
10
Expected Output:
Col1 Col3
834 1
834 10
877 10
900 1
This is what I have done so far:
select distinct t1.Col1,A.Col3
from Table1
cross apply
(select * from Table2 left join Table1 on Col2 = Col3) A
order by t1.Col1,A.Col3
I have been trying lot using join, cross apply and other sql function to get me the expected output. Any help is appreciated.
Logic:
I want to get the values of Col1 of Table1 for which Col3 does not matches with col2 of Table1.
For Eg: Values 1 and 10 of Col3 of table2 is not there for value 834 of col1 of table1. Hence there are two rows for 834, one with value 1 and other with 10.
Please try with the below code snippet.
DECLARE #Table1 TABLE(
Col1 INT NOT NULL,
Col2 INT NOT NULL
);
INSERT INTO #Table1 VALUES(834 , 2)
INSERT INTO #Table1 VALUES(834 , 3)
INSERT INTO #Table1 VALUES(834 , 5)
INSERT INTO #Table1 VALUES(877 , 1)
INSERT INTO #Table1 VALUES(877 , 2)
INSERT INTO #Table1 VALUES(877 , 5)
INSERT INTO #Table1 VALUES(900 , 10)
INSERT INTO #Table1 VALUES(900 , 2)
INSERT INTO #Table1 VALUES(900 , 3)
DECLARE #Table2 TABLE(
Col3 INT NOT NULL
);
INSERT INTO #Table2 VALUES(1)
INSERT INTO #Table2 VALUES(10)
SELECT a.Col1,a.Col3 FROM (SELECT DISTINCT a.Col1,b.Col3 FROM #Table1 a,#Table2 b
WHERE a.Col2 <> b.Col3) a
LEFT JOIN #Table1 c on a.Col1 = c.Col1 and a.Col3 = c.Col2
WHERE c.Col1 is null
I doubt you need any join in here. All you want to select from table1 are the rows with matching value in table2. Something like this :
Select distinct col1, col2 from table1
Where col2 not in (select col3 from table2)
select a.col1, a.col2
from Table1 a
where not exists(select * from Table2 b where a.col1 = b.col3)
This may work...

Join based on the value to different table

Hi everyone I have a table TableC which saves primary key values from two different tables TableA and TableB. because they are primary keys from two tables I could have end up with duplicates in that tableC so when Storing values I prefixed the Primary keys with a short text to differentiate that which value is coming from which table.
Now I would like to Join this tableC with TableA and TableB to get the data from tableA and TableB
TableC :
ID_Column
1A
1B
2A
TableA:
ID_Column | Data
1 | data A 1
2 | data A 2
3 | data A 3
TableB:
ID_Column | Data
1 | data B 1
2 | data B 2
3 | data B 3
This is what I have been trying to do
select C.ID_Column, data
from tableC C
inner join tableA A
on A.ID_Column = left(C.ID_Column, 1)
inner join tableB B
on B.ID_Column = left(C.ID_Column, 1)
this will return data from both tables I want to return data from table b when ID_Column has B in the end and want to return data from tableA when ID_Column has A in the end
Thank you in advance.
Well, TableC should really have at least 2 columns, one for the id and one to identify to which table it belongs. Anyway, this could be done this way:
SELECT C.ID_Column,
ISNULL(A.Data,B.Data) Data
FROM TableC C
LEFT JOIN TableA A
ON LEFT(C.ID_Column,LEN(C.ID_Column)-1) = A.ID_Column
AND RIGHT(C.ID_Column,1) = 'A'
LEFT JOIN TableB B
ON LEFT(C.ID_Column,LEN(C.ID_Column)-1) = B.ID_Column
AND RIGHT(C.ID_Column,1) = 'B'
The results are:
╔══════════╦══════════╗
║ D_COLUMN ║ DATA ║
╠══════════╬══════════╣
║ 1A ║ data A 1 ║
║ 1B ║ data B 1 ║
║ 2A ║ data A 2 ║
╚══════════╩══════════╝
And here is a demo for you to try.
You'll obviously need to tweak this a bit, but could you consider refactoring table C just a bit. Seperate the two out and this will eliminate the calculation in the join (not a good performance tactic).
--Create Table A
IF OBJECT_ID('tempdb..#TableA') IS NOT NULL DROP TABLE #TableA
CREATE TABLE #TableA (ID_COLUMN INT, DATA VARCHAR(max))
INSERT INTO #TableA(ID_COLUMN,DATA) VALUES (1,'data A 1'),(2,'data A 2'),(3,'data A 3')
--Create Table B
IF OBJECT_ID('tempdb..#TableB') IS NOT NULL DROP TABLE #TableB
CREATE TABLE #TableB (ID_COLUMN INT, DATA VARCHAR(max))
INSERT INTO #TableB (ID_COLUMN,DATA) VALUES (1,'data B 1'),(2,'data B 2'),(3,'data B 3')
--Create Table C
IF OBJECT_ID('tempdb..#TableC') IS NOT NULL DROP TABLE #TableC
CREATE TABLE #TableC (ID_COLUMN INT, ORIGIN_TABLE CHAR(1))
INSERT INTO #TableC (ID_COLUMN, ORIGIN_TABLE) VALUES (1,'A'), (1,'B'),(2,'A')
SELECT A.ID_COLUMN, A.DATA
FROM #TableC AS C
INNER JOIN #TableA AS A ON (C.ID_COLUMN = A.ID_COLUMN)
WHERE C.ORIGIN_TABLE = 'A'
UNION ALL
SELECT B.ID_COLUMN, B.DATA
FROM #TableC AS C
INNER JOIN #TableB AS B ON (C.ID_COLUMN = B.ID_COLUMN)
WHERE C.ORIGIN_TABLE = 'B'

Resources