Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLite: group_concat() multiple columns

Tags:

sqlite

I has a problem:

In my SQLite (sqlite3 on android) database I have a table like so

company |  name    | job
--------------------------
      1 |  'Peter' | 'Manager'
      1 |  'Jim'   | (null)
      2 |  'John'  | 'CEO'
      2 |  'Alex'  | 'Developer'
      3 |  'Lisa'  | (null)

and I'd like to get to

company | formated
--------------------------------------
      1 | 'Peter (Manager), Jim'
      2 | 'John (CEO), Alex (Developer)'
      3 | 'Lisa'

What I got so far is

SELECT group_concat(concat) FROM (
    SELECT
        CASE 
            WHEN job IS NULL THEN name
            ELSE name || ' (' || job || ')'
        END AS concat
    FROM jobs
)

which gives me all in one string

'Peter (Manager), Jim, John (CEO), Alex (Developer), Lisa'

Although that is quite good already, it's still not what I want. And at that point I fail to understand how I have to combine things to get what I want.

On a sidenote: Is there any good tutorial on complexer queries? So far I've only found some snippets but nothing that really explains how such a thing can be built

like image 362
zapl Avatar asked Mar 21 '12 01:03

zapl


1 Answers

You were close!

SELECT 
    company,
    group_concat(concat) AS formated
FROM (
    SELECT
        company,
        CASE 
            WHEN job IS NULL THEN name
            ELSE name || ' (' || job || ')'
        END AS concat
    FROM jobs
)
GROUP BY company
like image 168
Eugen Rieck Avatar answered Nov 15 '22 20:11

Eugen Rieck