SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Merging two rows into one in the same table
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

mmalaka
Starting Member

Ireland
33 Posts

Posted - 03/04/2013 :  09:35:25  Show Profile  Visit mmalaka's Homepage  Reply with Quote
Let us say we have a table with the following fields and values

Field1, Field2, Field3, Field4
------------------------------
Name1, String1, 10 , Test1
Name1, String1, 20 , Test2


I want to merge those records into the same record so that the result
would be...


Field1, Field2, Field3, Field4
------------------------------
Name1, String1, 30 , Test1


The important part is to have a distinct Field2 and the sum of values of Field3 when Field1 and Field2 are the same...

Any advice please?




James K
Flowing Fount of Yak Knowledge

3323 Posts

Posted - 03/04/2013 :  10:01:55  Show Profile  Reply with Quote
What is the rule for Field4 that causes Test1 to be picked rather than Test2?
SELECT Field1, Field2, SUM(Field3) AS Field3,MIN(Field4) AS Field4
FROM TheTable
GROUP BY Field1, Field2;
Go to Top of Page

mmalaka
Starting Member

Ireland
33 Posts

Posted - 03/04/2013 :  10:03:54  Show Profile  Visit mmalaka's Homepage  Reply with Quote
There is no role...I do not care about it..but I need to select a value from both records...randomly or the top 1...
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52249 Posts

Posted - 03/04/2013 :  23:04:41  Show Profile  Reply with Quote
quote:
Originally posted by mmalaka

There is no role...I do not care about it..but I need to select a value from both records...randomly or the top 1...

ok then James suggestion or below would do

SELECT  Field1, Field2,Field3, Field4
FROM
(
SELECT Field1, Field2, SUM(Field3) OVER PARTITION BY (Field1, Field2) AS Field3, Field4,ROW_NUMBER() OVER (PARTITION BY Field1, Field2 ORDER BY Field4) AS Seq
FROM Table
)t
WHERE Seq=1


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000