mercredi 14 octobre 2015

SQL query using GROUP_CONCAT() function

The below table contains Id - PK and its Parent Id in some case. We can consider is as Activities done by a user. So if it is a parent Activity, then parent should be null otherwise it should have some value. E.g. somebody comments on a facebook post and somebody else comments on another comment. So for comment the parent Id will be the post Id but the post will not have any parent id.

Type is to say whether its a post or a comment or a like. by is for telling who did this activity.

Table Name - Activity

|  Id  |  parent  |  type  |  by    |
-------------------------------------
|  100 |  NULL    |  A     | 100    |
|  200 |  100     |  B     | 200    |
|  300 |  100     |  B     | 300    |
|  400 |  100     |  B     | 400    |
|  500 |  NULL    |  A     | 100    |
|  600 |  500     |  B     | 600    |

Table Name - User

|  Id  |  name    |
-------------------
|  100 |  Amit    |
|  200 |  Alok    |
|  300 |  Arjun   |
|  400 |  Arpeet  |
|  600 |  Amaan   |

The output should be

|  Id  |  name  |  Groups             |
---------------------------------------
|  100 |  Amit  |  Alok, Arjun, Arpeet|
|  500 |  Amit  |  Amaan              |

NOTE - I don't want this to be achieved using FOR XML PATH since it is not supported in SQLite which I am working on.

My query attempt was

SELECT  t.id, n.name,
(select group_concat(n.name) from activity t, user n where n.id = t.id and t.type = 'B'
group by t.parent) as  groups
FROM activity t, user n
WHERE n.id = t.id  and t.type = 'A'

The result I got was

|  Id  |  name  |  Groups             |
---------------------------------------
|  100 |  Amit  |  Alok, Arjun, Arpeet|

You can see that the other row was missing from result.

Aucun commentaire:

Enregistrer un commentaire