473,783 Members | 2,350 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Combine rows in a table that are only different in one column

denny1824
32 New Member
Hi everyone,

Here is my problem. I have a Table Variable (I could easily turn it into a Temp Table instead) that will sometimes have rows that are identical except for one specific column. The column is of nvarchar. When the rest of the columns for those rows are identical, I want to combine all of the values of that column into a single nvarchar with a delimiter in between each value. Then combine the rows where all of the other columns are the same and that specific column now have the single nvarchar.

Another complexity to this is that if that specific column has a null, then I dont want that row combined with the others.

Example:
Expand|Select|Wrap|Line Numbers
  1. DECLARE @Table1 TABLE
  2. (
  3.     ID int,
  4.     Column1 nvarchar(10),
  5.     Column2 nvarchar(10),
  6.     Column3 nvarchar(10),
  7.     ColumnX nvarchar(1000)
  8. )
  9.  
  10. INSERT INTO @Table1 VALUES (1, 'Value1', 'Value2', 'Value3', NULL)
  11. INSERT INTO @Table1 VALUES (1, 'Value1', 'Value2', 'Value3', 'ValueX1')
  12. INSERT INTO @Table1 VALUES (1, 'Value1', 'Value2', 'Value3', 'ValueX2')
  13. INSERT INTO @Table1 VALUES (1, 'Value1', 'Value2', 'Value3', 'ValueX3')
  14. INSERT INTO @Table1 VALUES (1, 'Value1', 'Value2', 'Value3', 'ValueX4')
  15.  
The Desired Result Is:
Expand|Select|Wrap|Line Numbers
  1. ID, Column1, Column2, Column3, ColumnX
  2.  1, 'Value1', 'Value2', 'Value3', NULL
  3.  1, 'Value1', 'Value2', 'Value3', 'ValueX1<br/>ValueX2<br/>ValueX3<br/>ValueX4'
  4.  
Any suggestion on how I should start to tackle this problem would be very helpful. I will be working on this on Monday morning. I am using T-SQL.

Thank You,
Denny
Feb 1 '08 #1
2 5722
Delerna
1,134 Recognized Expert Top Contributor
Yes, it would be nice to be able to say

Expand|Select|Wrap|Line Numbers
  1.    SELECT ID,Column1,Coulmn2,Column3,concat(Columnx) as Columnx
  2.    FROM @Table1 
  3.    GROUP BY ID,Column1,Coulmn2,Column3
  4.  
and the database egine would just add the strings togeter with a comma separator. Unfortunately there is no such aggregate as concat().

I have done in the past and I think I resorted to a cursor to achieve it.
I believe to do it with a query instead
you will need to be able to sequence each identical ID,Column1,Coul mn2,Column3 from 1 to however many identical records there are in each particular group.

Then you could say something like
Expand|Select|Wrap|Line Numbers
  1. SELECT ID,Column1,Coulmn2,Column3,Max(ColumnX1) + ',' + Max(ColumnX2) + etc etc etc as Columnx 
  2. FROM
  3. (   SELECT ID,Column1,Coulmn2,Column3
  4.                 ,case when SeqNo=1 then ColumnX else'' end as ColumnX1
  5.                 ,case when SeqNo=2 then ColumnX else'' end as ColumnX2
  6.                 , etc etc etc
  7.     FROM
  8.     @Table1
  9. )a 
  10. GROUP BY ID,Column1,Coulmn2,Column3
  11.  
of course the practicalities of doing something like that is dependent on the maximum number of different values in any particular group of ID,Column1,Coul mn2,Column3.


Good luck with that and its no wonder im going bald
Feb 4 '08 #2
denny1824
32 New Member
Thank you Delerna.

I am not allowed to use cursors, so I had to use an alternative way to loop. I also had to add an identity to the original table. Here is my result:

Expand|Select|Wrap|Line Numbers
  1. DECLARE @Table1 TABLE
  2. (
  3.     RowCounter int identity (1,1),
  4.     ID int,
  5.     Column1 nvarchar(10),
  6.     Column2 nvarchar(10),
  7.     Column3 nvarchar(10),
  8.     ColumnX nvarchar(10)
  9. )
  10.  
  11. INSERT INTO @Table1 VALUES (1, 'Value11', 'Value12', 'Value13', NULL)
  12. INSERT INTO @Table1 VALUES (1, 'Value11', 'Value12', 'Value13', 'Value1X1')
  13. INSERT INTO @Table1 VALUES (1, 'Value11', 'Value12', 'Value13', 'Value1X2')
  14. INSERT INTO @Table1 VALUES (1, 'Value11', 'Value12', 'Value13', 'Value1X3')
  15. INSERT INTO @Table1 VALUES (1, 'Value11', 'Value12', 'Value13', 'Value1X4')
  16. INSERT INTO @Table1 VALUES (2, 'Value21', 'Value22', 'Value23', NULL)
  17. INSERT INTO @Table1 VALUES (2, 'Value21', 'Value22', 'Value23', 'Value2X1')
  18. INSERT INTO @Table1 VALUES (2, 'Value21', 'Value22', 'Value23', 'Value2X2')
  19. INSERT INTO @Table1 VALUES (2, 'Value21', 'Value22', 'Value23', 'Value2X3')
  20. INSERT INTO @Table1 VALUES (2, 'Value21', 'Value22', 'Value23', 'Value2X4')
  21.  
  22. DECLARE    @iCounter INT,
  23.     @iLoop INT, 
  24.     @iID INT
  25.  
  26. DECLARE @Result TABLE
  27. (
  28.     ID int,
  29.     Column1 nvarchar(10),
  30.     Column2 nvarchar(10),
  31.     Column3 nvarchar(10),
  32.     ColumnX nvarchar(1000)
  33. )
  34.  
  35. SET @iCounter = 1
  36. SELECT @iLoop = Max(RowCounter) FROM @Table1
  37.  
  38. WHILE @iCounter <= @iLoop
  39. BEGIN
  40. SELECT @iID = ID FROM @Table1 WHERE RowCounter = @iCounter
  41. IF @iID IS NOT NULL
  42. IF (NOT EXISTS (SELECT * FROM @Result WHERE ID = @iID AND ColumnX IS NOT NULL) --This ID is not yet in result table
  43.     OR EXISTS(SELECT * FROM @Table1 WHERE RowCounter = @iCounter AND ColumnX IS NULL) --OR the ColumnX is null
  44. )
  45. BEGIN
  46.     INSERT INTO @Result SELECT ID,Column1,Column2,Column3,ColumnX 
  47.         FROM @Table1 WHERE RowCounter = @iCounter --Add Row to result table
  48.     DELETE @Table1 WHERE RowCounter = @iCounter --Remove row from initial table
  49. END
  50. ELSE --A row with ID = @iID and a non-null ColumnX already exists in result table 
  51. BEGIN
  52.     UPDATE @Result SET ColumnX = ColumnX + '<br/>' + (SELECT ColumnX FROM @Table1 WHERE RowCounter = @iCounter)
  53.     FROM @Result WHERE ID = @iID AND ColumnX IS NOT NULL --Update ColumnX
  54.     DELETE @Table1 WHERE RowCounter = @iCounter --Remove row from initial table
  55. END
  56.  
  57. SET @iCounter = @iCounter + 1
  58. END
  59.  
  60. SELECT * FROM @Result
The Desired Resulting Table Is:

Expand|Select|Wrap|Line Numbers
  1. ID, Column1, Column2, Column3, ColumnX 
  2. 1, Value11, Value12, Value13, NULL
  3. 1, Value11, Value12, Value13, Value1X1<br/>Value1X2<br/>Value1X3<br/>Value1X4
  4. 2, Value21, Value22, Value23, NULL
  5. 2, Value21, Value22, Value23, Value2X1<br/>Value2X2<br/>Value2X3<br/>Value2X4
Thanks again,
Denny
Feb 4 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

9
3732
by: Steve Jorgensen | last post by:
Hi all, I'm working on the schema for a database that must represent data about stock & bond funds over time. My connundrum is that, for any of several dimension fields, including the fund name itself, the dimension may be represented in different ways over time, and may split or combine from one period to the next. When querying from the database for an arbitrary time period, I need the data to be rolled up to the smallest extent...
6
9414
by: Fan Ruo Xin | last post by:
I try to copy a table from production system (DB2 UDB EEE V7.2 + fixpak5) to the testing system (DB2 UDB V8.1 + fixpak4a). I moved the data from productions system by using the following steps: On production system: $ db2 "export to xxxxx.del of del select * from xxxxxx" On testing system: I use db2 utility autoload, because I use the autoload cfg script for a long
8
7104
by: mark | last post by:
Access2000 How do I write a query that combines the CTC field from each record below into one record? I need to concatenate the CTC field with a separator, like below: BattID VehicleID STDATE STTIME CTC LKO500HF 00000000 10/27/2003 4:13:51 AM 4 LKO500HF 00000000 10/27/2003 5:13:51 AM 5 LKO500HF 00000000 10/27/2003 10:13:51 AM 6 LKO500HF 00000000 10/27/2003 11:13:51 AM 4
3
11521
by: Stephen Matthews | last post by:
Help please i have a file which im importing, however it is a single column, the data looks like C8517673505 N7062175 C8517673516 N7062178 C8517673527
14
2413
by: imani_technology_spam | last post by:
I have the following table; CREATE TABLE ( IDENTITY (1, 1) NOT NULL , (7200) COLLATE SQL_Latin1_General_Pref_CP1_CI_AS NOT NULL , CONSTRAINT PRIMARY KEY CLUSTERED ( ,
7
43140
by: Mintyman | last post by:
Hi, I'm working on a system migration and I need to combine data from multiple rows (with the same ID) into one comma separated string. This is how the data is at the moment: Company_ID Material 0x00C00000000053B86 Lead 0x00C00000000053B86 Sulphur 0x00C00000000053B86 Concrete
1
2639
by: ktang3227 | last post by:
Hi all, I have a table which list all the different product# and quantity of the product in each row. But for some reason, some of the product splites into 2 rows. For example; Product A has a quantity of 30, then it will shows like this: Product A 15 Product A 15
1
3418
by: bluereign | last post by:
Thank you for your assistance. I am a novice looking to JOIN and append or combine records from 2 current Tables into 2 new Tables named below. I have been able to JOIN Tables with the script below. My problem is if I don’t use the WHERE clause in my script below, the script can query up to 3 records with the same “LoanNo” due to the fact that there can be up to 3 “TypeCodes” in each Table (Borrower, Co-Borrower 1 and Co-Borrower 2...
2
4996
by: mzmatterafact | last post by:
I'm back and please be warned I'm a total NEWBIE, and i've had success with my previous post so I would like to buy another vowel! Now i have taken my csv file and imported to a DataTable, i've parsed out the rows and columns to match two colums in SQL. If the two fields match, i want to create a record on a SQL Table. The problem is, I have 4 fields in the CSV file that I would like to "Concatenate" (don't know the syntax for c#) the first...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10081
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7494
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4044
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2875
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.