I think you need to do a self join:
SELECT T.ID,
T.TheValue,
GROUP_CONCAT(T2.ID) AS TheIds
FROM T
LEFT JOIN T T2
ON T2.TheValue = T.TheValue
AND T2.ID != T.ID
GROUP BY T.ID, T.TheValue;
Question
Hope the title makes sense!
Given a table MyTable with these values
ID TheValue
A 1
B 2
C 3
D 1
E 1
F 2
I can use
SELECT
TheValue,
group_concat(concat) AS TheIDs
FROM (
SELECT distinct
TheValue,
ID AS concat
FROM MyTable)
GROUP BY TheValue
to get
TheValue TheIDs
1 A,B,D
2 B,F
3 C
How can I instead get a result of ID, TheValue and the 'Other' IDs, not including the ID on that row?
eg
ID TheValue OtherIDs
A 1 D,E
B 2 F
C 3 <null> (or empty string, I don't mind)
D 1 A,E
E 1 A,D
F 2 B
(I'm using SQLite in case an answer is dialect specific)
Solution
I think you need to do a self join:
SELECT T.ID,
T.TheValue,
GROUP_CONCAT(T2.ID) AS TheIds
FROM T
LEFT JOIN T T2
ON T2.TheValue = T.TheValue
AND T2.ID != T.ID
GROUP BY T.ID, T.TheValue;
OTHER TIPS
The first expected output from your question implies somehow that you need to normalize your database scheme, and to say, your Value is an ID and your IDs are values!
SELECT
TheValue,
group_concat(ID) AS TheIDs
FROM MyTable
GROUP BY TheValue
Should do the job (at least in MySQL, I think in sqlite too).