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
4 23035
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
michaelb 534
Recognized Expert Contributor
This should work for you -
CREATE or replace FUNCTION flatten() RETURNS integer AS $$
-
DECLARE
-
rec RECORD ;
-
cnt integer ;
-
delim varchar := '/';
-
BEGIN
-
FOR rec IN SELECT * FROM tab1 ORDER BY ID LOOP
-
select count(1) into cnt from tab2 where tab2.ID = rec.ID;
-
if cnt = 0 then
-
insert into tab2 values (rec.ID, rec.roadnum);
-
else
-
update tab2 set roadnum = roadnum || delim || rec.roadnum
-
where tab2.ID = rec.ID;
-
end if;
-
END LOOP;
-
-
RETURN (select count (*) from tab2);
-
END;
-
$$ LANGUAGE plpgsql;
-
here's the result of running select flatten(); -
postgres=# select * from tab1;
-
id | roadnum
-
-------+-----
-
1 | A1
-
2 | B1
-
2 | B2
-
3 | C1
-
3 | C2
-
3 | C3
-
4 | D1
-
4 | D2
-
4 | D3
-
4 | D4
-
5 | E1
-
6 | F1
-
7 | G1
-
7 | G2
-
8 | J1
-
8 | J2
-
9 | H1
-
10 | K1
-
(18 rows)
-
-
-
postgres=# select * from tab2;
-
id | roadnum
-
-------+-------------
-
1 | A1
-
2 | B1/B2
-
3 | C1/C2/C3
-
4 | D1/D2/D3/D4
-
5 | E1
-
6 | F1
-
7 | G1/G2
-
8 | J1/J2
-
9 | H1
-
10 | K1
-
(10 rows)
-
You may find this useful: -
SELECT array_to_string(array(SELECT column_name FROM table_name), ':');
-
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. -
SELECT array_to_string(array(SELECT roadnum FROM table_name WHERE ID=4), ':');
-
would return "N-3:E-2:CA-1" .
Powerful!
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;
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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
|
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
|
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
|
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...
| |
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...
|
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...
|
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
|
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
|
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...
|
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...
| |
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...
|
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...
|
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();...
|
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...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |