问题
I have a dataset that looks like this
RID SID MID QID QText
------------------------------------------------------------------
NULL NULL NULL 10,20,30 't1','t2','t3'
10 14 13 4 'text2'
100 141 131 5,6 't5','t6'
I'd like to run some sql command that would basically take the row with the nulls and concatenate the QID and QText columns to each row that has a valid RID, SID, MID
so the end result would be a dataset similar to this (in this case the first row doesn't need to be there because I've concatenated the info I've got in that row to the other rows).
RID SID MID QID QText
------------------------------------------------------------------
NULL NULL NULL 10,20,30 't1','t2','t3'
10 14 13 4,10,20,30 'text2','t1','t2','t3'
100 141 131 5,6,10,20,30 't5','t6','t1','t2','t3'
I've tried several group_concats with different grouping but can't quite get it to work the way I need it to. Is this transform possible with raw SQL (mysql) ?
Some of what I've tried so far (really bad attempts because I just don't know what will do what I'm trying to do) are
select group_concat(QText) from myTable group by ? <--- I don't know of anything that I can group by that will give me what i'm looking for. That's what I mean by really bad attempts. I know they are wrong (group by id, qid, etc, etc). Also thought about and tried a sum on the columns that I want to concatenate.
回答1:
If you want the NULL row(s) to be grouped with all non-NULL rows, make a copy for every group. You could, for instance, derive the list of distinct RID, SID, MID
combinations
SELECT DISTINCT RID, SID, MID, QID, QText
FROM myTable
WHERE RID IS NOT NULL
OR SID IS NOT NULL
OR MID IS NOT NULL
and cross join it with the NULL row(s):
SELECT
groups.RID, groups.SID, groups.MID,
empty.QID, empty.QText
FROM
(
SELECT DISTINCT RID, SID, MID
FROM myTable
WHERE RID IS NOT NULL
OR SID IS NOT NULL
OR MID IS NOT NULL
) AS groups
CROSS JOIN
(
SELECT QID, QText
FROM myTable
WHERE RID IS NULL
AND SID IS NULL
AND MID IS NULL
) AS empty
then combine the resulting set with the original set:
SELECT RID, SID, MID, QID, QText
FROM myTable
UNION ALL
SELECT
groups.RID, groups.SID, groups.MID,
empty.QID, empty.QText
FROM
(
SELECT DISTINCT RID, SID, MID
FROM myTable
WHERE RID IS NOT NULL
OR SID IS NOT NULL
OR MID IS NOT NULL
) AS groups
CROSS JOIN
(
SELECT QID, QText
FROM myTable
WHERE RID IS NULL
AND SID IS NULL
AND MID IS NULL
) AS empty
Now just use the combined result set as a derived table and get your GROUP_CONCATs from it:
SELECT
RID, SID, MID,
GROUP_CONCAT(QID) AS QID,
GROUP_CONCAT(QText) AS QText
FROM
(
SELECT … /* the above UNION ALL query here */
) AS s
GROUP BY
RID, SID, MID
;
来源:https://stackoverflow.com/questions/24642371/concatenate-certain-columns-across-multiple-rows