0

I have created an SQL query that merges duplicates in a table:

SELECT Min([XNbr]) AS [XNbr], [ZNbr], [Hamster], [Cat], [Cow], [Dog],
[Squirrel], [Bird], [Mouse], [Flower], [Tree], Max([TimeStamp]) AS
[TimeStamp]
FROM dbo.Sunshine
GROUP BY [ZNbr], [Hamster], [Cat], [Cow], [Dog], [Squirrel], [Bird],
[Mouse], [Flower], [Tree]
ORDER BY [XNbr]

I now want to extend this query to transfer the result in target table I created before that has the exact structure (same fields and types) of the query above. How can that be done?

2
  • What's wrong with simply INSERT? Commented May 30, 2017 at 8:14
  • To create the table on the fly use SELECT INTO. To insert into an existing table, use INSERT SELECT Commented May 30, 2017 at 8:42

3 Answers 3

0

You need just INSERT INTO :

INSERT INTO TargetTable (Columns)
SELECT Min([XNbr]) AS [XNbr], [ZNbr], [Hamster], [Cat], [Cow], [Dog],
[Squirrel], [Bird], [Mouse], [Flower], [Tree], Max([TimeStamp]) AS
[TimeStamp]
FROM dbo.Sunshine
GROUP BY [ZNbr], [Hamster], [Cat], [Cow], [Dog], [Squirrel], [Bird],
[Mouse], [Flower], [Tree]
ORDER BY [XNbr]
Sign up to request clarification or add additional context in comments.

Comments

0

You can use Insert Into Select Syntax. Visit this link to refer more: https://www.w3schools.com/sql/sql_insert_into_select.asp

Comments

0

Store the result temporarily in the table.

Use 'generate scrips' option in the sql server and chose the table created.

Generate script for both schema and data

http://www.c-sharpcorner.com/UploadFile/26b237/generate-database-script-in-sql-server-2012/

After generating the script, just change the table name.

Or

If the target table doesn't exist in the database then,

 SELECT Min([XNbr]) AS [XNbr], [ZNbr], [Hamster], [Cat], [Cow], [Dog], [Squirrel], [Bird], [Mouse], [Flower], [Tree], Max([TimeStamp]) AS [TimeStamp]                                     
 into TargetTable 
 FROM dbo.Sunshine 
 GROUP BY [ZNbr], [Hamster], [Cat], [Cow], [Dog], [Squirrel], [Bird], [Mouse], [Flower], [Tree] 
 ORDER BY [XNbr]

The generated table will have the same schema as the result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.