Insert distinct values from one table into another table
Whenever you think about doing something in a loop, step back, and think again. SQL is optimized to work with sets. You can do this using a set-based query without the need to loop:
INSERT dbo.table1(id) SELECT DISTINCT id FROM dbo.table0;
There are some edge cases where looping can make more sense, but as SQL Server matures and more functionality is added, those edge cases get narrower and narrower...
Insert into table with multiple select including select distinct from two tables
I think you want insert . . . select
with join
:
insert into Table3 (companyid, certno, expdate, createddate, is_null)
select distinct t2.companyid, t1.certno, t1.expdate, getdate(), 1
from Table1 t1 join
Table2 t2
on t1.company = t2.company
where t1.company like '%ABC%';
You can remove the where
clause to insert all companies in one insert
.
Select unique records and insert into another table avoiding duplicates in it
SQL DEMO
You can use GROUP BY and EXISTS in sql server like below :
insert into userto (username, date)
select distinct username, date from userfrom uf
where
not exists(select 1 from userto where username=uf.username and date=uf.date)
SELECT DISTINCT values and INSERT INTO table
You can use INSERT INTO... SELECT
statement on this,
INSERT INTO tableName (A, B, C)
SELECT A, B, MAX(C) + 1
FROM tableName
GROUP BY A, B
- SQLFiddle Demo
Insert distinct records from column in Table1 into column table 2 into row where they match on a different column
You should use Merge Statement:
MERGE Inventory AS target
USING (SELECT Name, ProductName FROM Product) AS source (ProductID, ProductName)
ON (target.ProductID = source.ProductID)
WHEN MATCHED
THEN UPDATE SET Name = source.ProductName
WHEN NOT MATCHED
THEN INSERT (ProductID, Name)
VALUES (source.ProductID, source.ProductName);
You can find more here:https://msdn.microsoft.com/es-es/library/bb510625(v=sql.120).aspx
Related Topics
Select and Count in One Query from Two Tables With MySQL
How to Return the Most Recent Logtime for Each Sku
How to Get Last 7 Days Data from Current Datetime to Last 7 Days in SQL Server
How to Select Last 5 Rows in a Table Without Sorting
How to Count Number of Digits After a Decimal Place
Calling an API from SQL Server Stored Procedure
Combine Multiple Columns from Database into One Column
Find All Parent Records Where All Child Records Have a Given Value (But Not Just Some Child Records)
List All Employee'S Names and Their Managers by Manager Name Using an Inner Join
How to Retrieve Microseconds or Milliseconds from MySQL Current Time
Convert a 12 Hour Format to 24 Hour Format in SQL Server
Update Only Time from My Datetime Field in SQL
How to Calculate Date Difference in Postgresql
Query to Get the Customers Who Haven't Transacted in the Past Two Months
Mysql Left Join Not Returning Null for Missing Rows
Oracle SQL Get the First and Last Records from an Ordered Dataset