473,672 Members | 2,450 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Aggregate/concatenate function (flattening columns into a row)

6 New Member
Hi Forum,

I'm trying to perform a type of concatenate function on a table and am not really sure where to start. I'd like to aggregate the values from 'field' on their ID. To explain, my table is like this:

ID roadnum
1 A-1
2 B-1
2 E-1
3 N-1
4 N-3
4 E-2
4 CA-1
5 E-1

Which I'd like to transform to:

ID roadnum
1 A-1
2 B-1 / E-1
3 N-1
4 E-2 / CA-1 / N-3
5 E-1

I've been looking at various lists and forums but I've not been able to follow the explanations. Further down the line, instead of simply concatenating the field values, I'd like to concatenate according to the road importance- which is based on the roadnum, but one step at a time. When I have the values in the same field, I'll worry about the next step.

Matt
Jun 12 '07 #1
4 23035
shoonya
161 New Member
Hi Forum,

I'm trying to perform a type of concatenate function on a table and am not really sure where to start. I'd like to aggregate the values from 'field' on their ID. To explain, my table is like this:

ID roadnum
1 A-1
2 B-1
2 E-1
3 N-1
4 N-3
4 E-2
4 CA-1
5 E-1

Which I'd like to transform to:

ID roadnum
1 A-1
2 B-1 / E-1
3 N-1
4 E-2 / CA-1 / N-3
5 E-1

I've been looking at various lists and forums but I've not been able to follow the explanations. Further down the line, instead of simply concatenating the field values, I'd like to concatenate according to the road importance- which is based on the roadnum, but one step at a time. When I have the values in the same field, I'll worry about the next step.

Matt
you can use the array data tye
make the roadnum attribute an array and append the routes in the last
check array data type from postgreSQL documentation

but be careful as when you will select the array from databse using php or ny other language it will return only a string {value1,value2. ..}
so iterate nd make it an array

shoonya
Jun 14 '07 #2
michaelb
534 Recognized Expert Contributor
This should work for you

Expand|Select|Wrap|Line Numbers
  1. CREATE or replace FUNCTION flatten() RETURNS integer AS $$
  2. DECLARE
  3.     rec RECORD ;
  4.     cnt integer ;
  5.     delim varchar := '/';
  6. BEGIN
  7.      FOR rec IN SELECT * FROM tab1 ORDER BY ID LOOP
  8.         select count(1) into cnt from tab2 where tab2.ID = rec.ID;
  9.         if cnt = 0 then
  10.            insert into tab2 values (rec.ID, rec.roadnum);
  11.         else
  12.            update tab2 set roadnum = roadnum || delim || rec.roadnum 
  13.                where tab2.ID = rec.ID;
  14.         end if;
  15.     END LOOP;
  16.  
  17.     RETURN (select count (*) from tab2);
  18. END;
  19. $$ LANGUAGE plpgsql;
  20.  
here's the result of running select flatten();
Expand|Select|Wrap|Line Numbers
  1. postgres=# select * from tab1;
  2.   id   | roadnum
  3. -------+-----
  4.      1 | A1
  5.      2 | B1
  6.      2 | B2
  7.      3 | C1
  8.      3 | C2
  9.      3 | C3
  10.      4 | D1
  11.      4 | D2
  12.      4 | D3
  13.      4 | D4
  14.      5 | E1
  15.      6 | F1
  16.      7 | G1
  17.      7 | G2
  18.      8 | J1
  19.      8 | J2
  20.      9 | H1
  21.     10 | K1
  22. (18 rows)
  23.  
  24.  
  25. postgres=# select * from tab2;
  26.  id    | roadnum
  27. -------+-------------
  28.      1 | A1
  29.      2 | B1/B2
  30.      3 | C1/C2/C3
  31.      4 | D1/D2/D3/D4
  32.      5 | E1
  33.      6 | F1
  34.      7 | G1/G2
  35.      8 | J1/J2
  36.      9 | H1
  37.     10 | K1
  38. (10 rows)
  39.  
Jun 14 '07 #3
Liam
1 New Member
You may find this useful:
Expand|Select|Wrap|Line Numbers
  1. SELECT array_to_string(array(SELECT column_name FROM table_name), ':');
  2.  
Change the inner SELECT to any query that returns only one column.
This will concatenate all values into one string, with a ':' between each value.

Expand|Select|Wrap|Line Numbers
  1. SELECT array_to_string(array(SELECT roadnum FROM table_name WHERE ID=4), ':');
  2.  
would return "N-3:E-2:CA-1" .

Powerful!
Aug 8 '08 #4
srikanth2254
1 New Member
CREATE TABLE ABC
(
ID int,
roadnum varchar(50)
)



INSERT INTO ABC VALUES (1,'A-1');
INSERT INTO ABC VALUES (2,'B-1');
INSERT INTO ABC VALUES (2,'E-1');
INSERT INTO ABC VALUES (3,'N-1');
INSERT INTO ABC VALUES (4,'N-3');
INSERT INTO ABC VALUES (4,'E-2');
INSERT INTO ABC VALUES (4,'CA-1');
INSERT INTO ABC VALUES (5,'E-1');

SELECT * FROM ABC;


SELECT DISTINCT ID,
ARRAY_TO_STRING (ARRAY(SELECT ROADNUM FROM ABC WHERE ID=T1.ID),'/') AS
ROADNUM
FROM ABC T1;
Aug 13 '10 #5

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

Similar topics

0
6251
by: Nick Heppleston | last post by:
I have a concatenation problem and I was wondering if somebody might be able to offer some help :-) I have the following table structure holding product long descriptions: Part No (pn) Sequence (seq) Long Description (long_desc) --------------- --------------- ---------------------------------------- HL1450 10 This is part of a long description and HL1450 20 it overlaps onto several lines. I'm HL1450 30 having difficulty writing...
6
9986
by: Steven An | last post by:
Howdy, I need to write an update query with multiple aggregate functions. Here is an example: UPDATE t SET t.a = ( select avg(f.q) from dbo.foo f where f.p = t.y ), t.b = ( select sum(f.q) from dbo.foo f where f.p = t.y ) FROM dbo.test t
1
1387
by: Job Lot | last post by:
Is it possible to use Aggregate functions with GROUP BY Clauses on DataTable. I have a DataTable with following values: Date Amount Int Balance 1/1/2004 5000.00 50.00 5050.00 1/1/2004 4000.00 40.00 4040.00 1/2/2004 1000.00 10.00 1010.00 1/2/2204 2000.00 20.00 2020.00 1/3/2004 1500.00 15.00 1515.00 I want my resultant DataTable to show in DataGrid as
1
2252
by: sausage31 | last post by:
I have a table as follows.... Device LotID Result1 Result2 Result3 aaa 1 5 10 15 bbb 1 2 4 6 aaa 2 3 6 9 I need to determine the mean of all results for each LotID, so used the Row Average function described on the Microsoft Knowledge base, which gives
3
14307
by: MrNobody | last post by:
I've read that the expression property for DataColumns is used to "Sets or retrieves the expresssion used to filter rows, calculate the values in a column, or create an aggregate column.". I have seen examples on how to filter a column, but how would I filter out an entire row depending on the value of a column? For example, if I wanted to filter out every row in a multi-column table where the "Is Fubar" column equals "true", how would...
6
3073
by: Larry Menard | last post by:
Folks, I know that DB2 does not (yet?) support this, but I wonder if anyone can suggest a work-around. I've seen article http://www-128.ibm.com/developerworks/db2/library/techarticle/dm-0504greenstein/, which was very helpful for developing the scalar functions I needed, but it does not cover how to emulate aggregate functions. And I've seen Knut's dW article...
0
1410
by: Matthew Lunnon | last post by:
Hi, I have two tables and I want to get summary information from the second table for each row of the first table, I can see two ways to do this one is with the SQL below but since the first table is very big the group by takes along time and there is no need since it is unique. The second way is witha function which loops through each row in the first table and does the aggregate function for that row. Does anyone know of a way to do this...
3
12459
by: ncsthbell | last post by:
I am pulling my hair out on this! Seems like it should be easy, I just can not get it to work like I want. I know I am doing something wrong, so I hope someone can be so kind to guide me!!! I have 2 tables: Table1 - columns: Period FuelType Table2 - columns: Period
3
2969
by: Michael Howes | last post by:
I have many double that each have a few thousand numbers in them. I need to concatenate groups of these double arrays into a new set of double. I don't know the total # of points. I thought it would be fairly easy to add these different double arrays to different ArrayLists and then use ToArray to get all the numbers back in one array. Sort of a cheap concatenate so I don't need to loop through all the points or keep newing larger arrays
0
8932
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8831
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...
0
8683
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7449
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...
0
5707
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4230
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...
1
2821
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
2
2064
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1819
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.