This question already has answers here:
Comma separated results in SQL (5 answers)
Closed 2 days ago.
I have a table like
DateCol TaskID EventName
2017-09-25 10 A
2017-07-26 10 B
2017-07-27 10 A
2017-09-14 10 A
2017-07-25 10 B
2017-09-25 10 C
2017-09-28 11 A
2017-11-01 11 D
2017-11-01 11 C
.....many thousands of rows
What I'd like is an output that, for each TaskID, if events A and C (not any other combination) occurred on the same day (from DateCol), EventName column is "A+C". So in this case it would show
DateCol TaskID EventName
2017-09-25 10 A+C
2017-07-26 10 B
2017-07-27 10 A
2017-09-14 10 A
2017-07-25 10 B
2017-09-28 11 A
2017-11-01 11 D
2017-11-01 11 C
You can see that row
2017-09-25 10 A
and
2017-09-25 10 C
are now one row,
2017-09-25 10 A+C
but nothing else is changed.
What kind of SQL statement would I have to do to make such an adjustment?
3条答案
按热度按时间93ze6v8z1#
assumption : only combine 2 different EventName into 1.
a bit crude, but it should work.
if there are other scenario that this does not work, please post the sample data with the expected result
9bfwbjaz2#
I believe the most efficient way to do this would be a self-
JOIN
.SQL Fiddle
svujldwt3#
So first you need a primary key/ unique column for all row.Then we find all the row who have A and C on the same date. We can use selfjoin for this. Also I assume the
TaskId
betweenEventName
A and C is always the same.For example if the Table name is
TableX
and primary key column isPrimaryX
Then we union with the normal but the normal query do not take the same data from our previous query. For this we can use not in on column
PrimaryX