Insert into table from another table after sorting data of first table - sql

I am doing something like this in SP,
insert into #FilteredTbl select * from #MasterTbl
but now problem is that i want data of #MasterTbl sorted before adding into #FilteredTbl,
How can I do that ?

Maybe something like this:
INSERT INTO #FilteredTbl
SELECT * FROM #MasterTbl AS tbl
ORDER BY tbl.OrderbyColumn

Try following method to insert sort result into temp table. Use ROW_NUMBER to ORDER BY table result
DECLARE #FilteredTbl AS TABLE
(
RowID INT
[Column_1]
[Column_2]
.
.
)
insert into #FilteredTbl
select ROW_NUMBER()OVER(ORDER BY [ShortColumn]),[Field_1],[Field_2]... from #MasterTbl

You can use order by class in select statement
insert into #FilteredTbl
select * from #MasterTbl
order by <column name>

INSERT INTO #FilteredTbl SELECT * FROM #MasterTbl AS mtb ORDER BY mtb.OrderbyColumn [desc]
Here desc is optional if you want to order by your column in descending order than add ir otherwise no need to add

Please sort the table as you want before inserting into another table.
Like:
Select * From #MasterTbl m Order By m.ColumnName
then insert into your new table
Insert Into #FilterTbl Select * From #MasterTbl m Order By m.ColumnName [DESC]
You can also filter your #MasterTbl using Where Clause

You should add identity your table then It will sorted like that
CREATE TABLE #test (
s int IDENTITY (1, 1),
ID int,
Name varchar(50),
part int
);
INSERT INTO #test (ID,Name,Part)
SELECT ID, Name, Part FROM Table_1 ORDER BY ID DESC
SELECT * FROM #test

Related

Multi column exist statement

I am trying to insert data to a table from another where data is not already exists
The table I am inserting the data into
CREATE TABLE #T(Name VARCHAR(10),Unit INT, Id INT)
INSERT INTO #T
VALUES('AAA',10,100),('AAB',11,102),('AAC',12,130)
The table I am selecting the data from
CREATE TABLE #T1(Name VARCHAR(10),TypeId INT,Unit INT, Id INT)
INSERT INTO #T1
VALUES('AAA',3,10,100),('AAA',3,10,106)
In this case I want to select ('AAA',3,10,106) from #T1 because AAA,106 combination not exists in #T
Basically what I want is to populate unique Name and Id combination
I tried below which doesn't seems to work
SELECT *
FROM #T1
WHERE NOT EXISTS(SELECT * FROM #T)
You have to somehow correlate the two tables:
SELECT *
FROM #T1
WHERE NOT EXISTS(SELECT *
FROM #T
WHERE #T1.Name = #T.Name AND #T1.ID = #T.ID)
The above query essentially says: get me those records of table #T1 which do not have a related record in #T having the same Name and ID values.
Your best bet is probably to use a insert statement with a subquery. Something like this:
SQL Insert Into w/Subquery - Checking If Not Exists
Edit: If you're still stuck, try this--
INSERT INTO #T (Name, Unit, Id)
SELECT Name, Unit, Id
FROM #T1
WHERE
NOT EXISTS (SELECT Name, Unit, Id FROM #T
WHERE #T.Name = #T1.Name AND #T.Unit = #T1.Unit AND #T.Id = #T1.Id)

SQL Insert into Temp Table With Serial Number

I have a simple SQL Query like:
Select Distinct GroupCode
Into #TempTable
From MyTable
SELECT * FROM #TempTable
drop Table #TempTable
And its OutPut is as
Now, I also want a Serial Number Column like 1,2,3.... there in the Out put.
How can I achieve that?
Thanks
Just add row_number():
select row_number() over (order by (select NULL)) as id, GroupCode
into #TempTable
from (select distinct GroupCode from MyTable) t;
select *
from #TempTable;
drop Table #TempTable;
You can explicitly create the temp table and add an IDENTITY column for your serial numbers, like so:
create table #tmp(id int identity(1,1), groupcode uniqueidentifier)
insert into #tmp (groupcode)
Select Distinct GroupCode
from mytable
select * from #tmp
order by id
drop table #tmp

How can I order data and add a record to the first position of the data set?

I know I can create a temp table, insert records, order it and then use union afterwards, but I'm looking for alternative routes. I tried a cte, but I had to order the entire thing which doesn't work as my unioned record doesn't stay "on top".
Basically, I have at able with Id INT, Name VARCHAR(MAX) fields and I want to ORDER BY Name before I add an entry at the row[0] position in the return set. If I order after the union, the row I wanted at row[0] gets ordered with it.
Any ideas?
You were on the right track with a union query. Force the sort with static values.
select 0 sortfield, '' name, etc
union
select 1 sortfield, name, etc
from etc
order by sortfield, name.
CREATE TABLE #temp (
idnt INT IDENTITY(2) NOT NULL --This begins the identity col with a value of 2
,Id INT
,Name VARCHAR(MAX)
)
INSERT INTO #temp
SELECT
...
FROM myTable
ORDER BY Name
CREATE TABLE #tempAPPEND (
idnt INT IDENTITY(1) NOT NULL --This begins the identity col with a value of 1
,Id INT
,Name VARCHAR(MAX)
)
INSERT INTO #tempAPPEND (Id, Name)
VALUES ('34384','Pinal Dave') -- SAMPLE VALUES
SELECT * FROM #temp
UNION
SELECT * FROM #tempAPPEND
ORDER BY idnt

Inserting data into a temporary table

After having created a temporary table and declaring the data types like so;
CREATE TABLE #TempTable(
ID int,
Date datetime,
Name char(20))
How do I then insert the relevant data which is already held on a physical table within the database?
INSERT INTO #TempTable (ID, Date, Name)
SELECT id, date, name
FROM physical_table
To insert all data from all columns, just use this:
SELECT * INTO #TempTable
FROM OriginalTable
Don't forget to DROP the temporary table after you have finished with it and before you try creating it again:
DROP TABLE #TempTable
SELECT ID , Date , Name into #temp from [TableName]
My way of Insert in SQL Server. Also I usually check if a temporary table exists.
IF OBJECT_ID('tempdb..#MyTable') IS NOT NULL DROP Table #MyTable
SELECT b.Val as 'bVals'
INTO #MyTable
FROM OtherTable as b
SELECT *
INTO #TempTable
FROM table
I have provided two approaches to solve the same issue,
Solution 1: This approach includes 2 steps, first create a temporary table with
specified data type, next insert the value from the existing data
table.
CREATE TABLE #TempStudent(tempID int, tempName varchar(MAX) )
INSERT INTO #TempStudent(tempID, tempName) SELECT id, studName FROM students where id =1
SELECT * FROM #TempStudent
Solution 2: This approach is simple, where you can directly insert the values to
temporary table, where automatically the system take care of creating
the temp table with the same data type of original table.
SELECT id, studName INTO #TempStudent FROM students where id =1
SELECT * FROM #TempStudent
After you create the temp table you would just do a normal INSERT INTO () SELECT FROM
INSERT INTO #TempTable (id, Date, Name)
SELECT t.id, t.Date, t.Name
FROM yourTable t
The right query:
drop table #tmp_table
select new_acc_no, count(new_acc_no) as count1
into #tmp_table
from table
where unit_id = '0007'
group by unit_id, new_acc_no
having count(new_acc_no) > 1
insert into #temptable (col1, col2, col3)
select col1, col2, col3 from othertable
Note that this is considered poor practice:
insert into #temptable
select col1, col2, col3 from othertable
If the definition of the temp table were to change, the code could fail at runtime.
Basic operation of Temporary table is given below, modify and use as per your requirements,
-- CREATE A TEMP TABLE
CREATE TABLE #MyTempEmployeeTable(tempUserID varchar(MAX), tempUserName varchar(MAX) )
-- INSERT VALUE INTO A TEMP TABLE
INSERT INTO #MyTempEmployeeTable(tempUserID,tempUserName) SELECT userid,username FROM users where userid =21
-- QUERY A TEMP TABLE [This will work only in same session/Instance, not in other user session instance]
SELECT * FROM #MyTempEmployeeTable
-- DELETE VALUE IN TEMP TABLE
DELETE FROM #MyTempEmployeeTable
-- DROP A TEMP TABLE
DROP TABLE #MyTempEmployeeTable
INSERT INTO #TempTable(ID, Date, Name)
SELECT OtherID, OtherDate, OtherName FROM PhysicalTable
insert #temptable
select idfield, datefield, namefield from yourrealtable
All the above mentioned answers will almost fullfill the purpose. However, You need to drop the temp table after all the operation on it. You can follow-
INSERT INTO #TempTable (ID, Date, Name)
SELECT id, date, name
FROM physical_table;
IF OBJECT_ID('tempdb.dbo.#TempTable') IS NOT NULL
DROP TABLE #TempTable;

SQL Select Counter by Group

Here is the code I've written to create a scenario:
USE tempdb
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'dbo.Emp') AND type in (N'U'))
DROP TABLE Emp
GO
CREATE TABLE Emp(
EmpID Int Identity(10,1) Primary Key,
EmpGroupID Int)
GO
INSERT INTO Emp(EmpGroupID) VALUES(1000)
INSERT INTO Emp(EmpGroupID) VALUES(1000)
INSERT INTO Emp(EmpGroupID) VALUES(1000)
INSERT INTO Emp(EmpGroupID) VALUES(2000)
INSERT INTO Emp(EmpGroupID) VALUES(2000)
INSERT INTO Emp(EmpGroupID) VALUES(2000)
INSERT INTO Emp(EmpGroupID) VALUES(3000)
GO
SELECT * FROM Emp
ORDER BY EmpGroupID,EmpID
What I need is for each group to have a counter variable, incrementing by 1, such that all the rows for Group 1000 have counter=1, groupid=2000 has counter=2, groupid=3000 has counter=3.
SELECT ?,EmpID,EmpGroupID
FROM Emp
ORDER BY EmpGroupID,EmpID
-- The result I'm looking for is:
1,10,1000
1,11,1000
1,12,1000
2,13,2000
2,14,2000
2,15,2000
3,16,3000
You're describing a dense ranking of groups:
SELECT
DENSE_RANK() OVER (ORDER BY EmpGroupID) as Counter,
EmpID,
EmpGroupID
FROM Emp
ORDER BY EmpGroupID,EmpID
And here's some reference material: http://msdn.microsoft.com/en-us/library/ms189798.aspx
You mean, you need a query that produces textual output with the commas as shown?
Try:
SELECT Counter + ',' + EmpGroupID + ',' + EmpID
FROM Table
ORDER BY EmpGroupID
ORDER BY can have more than one clause
Try
SELECT Counter,EmpGroupID, EmpID
ORDER BY Counter,EmpGroupID, EmpID
Guessing from your description, do you want something like
SELECT EmpGroupID, EmpID, COUNT(1) AS Counter
FROM some-table-name
GROUP BY EmpGroupID, EmpID
ORDER BY COUNT(1), EmpGroupID, EmpID
That's for SQL Server - in other cases you may be able to say
ORDER BY Counter, EmpGroupID, EmpID
It took me a while to understand what you were asking. As I understand it, you want to create and populate the 'Counter' column based on the EmpGroupID? If so, then something like this:
SELECT EmpGroupID, EmpID,
(SELECT COUNT(*) +1
FROM [table]
WHERE t2.EmpGroupID < t1.EmpGroupID GROUP BY t2.EmpGroupID
) AS Counter
FROM [table] t1
ORDER BY EmpGroupID, EmpID
Try this:
SELECT DENSE_RANK() OVER (ORDER BY EmpID) as 'counter',GroupID
FROM Emp
ORDER BY counter, EmpGroupID