Last active
January 22, 2022 04:32
-
-
Save Abhinickz/3459fd6dc4867677b252f64fc42f2888 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE public.test ( | |
id SERIAL, | |
username varchar NULL, | |
name varchar NULL | |
); | |
INSERT INTO public.test (username, name) | |
VALUES | |
('Abhinickz','OWNER'), | |
('Abhasker','EMPLOYEE'), | |
('Abhishek','OWNER'), | |
('Bhasker','EMPLOYEE'); | |
SELECT * FROM test; | |
/* | |
id | username | name | |
----+-----------+---------- | |
| Abhinickz | OWNER | |
| Abhasker | EMPLOYEE | |
| Abhishek | OWNER | |
| Bhasker | EMPLOYEE | |
(4 rows) | |
*/ | |
SELECT | |
json_object_agg( | |
name, | |
data | |
) AS data | |
FROM ( | |
SELECT | |
name, | |
json_object_agg( | |
id, | |
username | |
) AS data | |
FROM test | |
GROUP BY name | |
) sq; | |
/* | |
data | |
----------------------------------------------------------------------------------------------------------- | |
{ "EMPLOYEE" : { "2" : "Abhasker", "4" : "Bhasker" }, "OWNER" : { "1" : "Abhinickz", "3" : "Abhishek" } } | |
(1 row) | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment