What I have is a chat from a telecom company signing up new customers. In the chat, a customer and company representative have a chat.
I am trying to collapse the chat, so that there are less rows. The diagrams below show how the before data looks like and how the after data needs to look like.
BEFORE
AFTER
I have looked at the following articles:
- SQL - How to combine rows based on unique values
- Optimal way to concatenate/aggregate strings
- How to sort the result from string_agg()
I have tried this code:
select
unique_id, string_agg(concat(text, ' ', text), ', ')
from
conversation
group by
unique_id, user
However, this does not collapse it as necessary. It collapses it entirely to 2x lines, one for customer and another for company. The logic I am looking for is If the next row in this query contains the same unique_id, user Then concatenate the current row text field with the next row text field.
Here is the SQL Fiddle page, but I am running this code in SQL Server which has string_agg
: http://sqlfiddle.com/#!9/5ad86c/3
I have requested an almost similar algorithm in R, if you look at my StackOverflow history.
CREATE TABLE conversation
(
`unique_id` double,
`line_no` int,
`user` varchar(7000),
`text` varchar(7000)
);
INSERT INTO conversation (`unique_id`, `line_no`, `user`, `text`)
VALUES
(50314585222, 1, 'customer', 'Hi I would like to sign up for a service'),
(50314585222, 2, 'company', 'Hi My name is Alex. We can offer the following plans. We also have signup bonuses, with doubling of data for 12 months '),
(50314585222, 3, 'company', 'Plan1: 40GB data, with monthly price of $80'),
(50314585222, 4, 'company', 'Plan2: 20GB data, with monthly price of $40'),
(50314585222, 5, 'company', 'Plan3: 5GB data, with monthly price of $15'),
(50314585222, 6, 'customer', 'I was hoping for a much smaller plan, with only voice service'),
(50314585222, 7, 'customer', 'maybe the $10 per month plan.'),
(50319875222, 4, 'customer', 'so how do I sign up'),
(50319875222, 5, 'customer', '*for the service'),
(50319875222, 7, 'company', 'maybe I can call you for your details?')
;