我想按照RecordId对要分组的下表进行分组,但我不想丢失任何数据。目前,我通过电子邮件进行分组,保留了所有数据。
Id | RecordId | Email | Message | ActionId | ---------------------------------------------------------------------- 1 | 2 | john@example.com | Record inserted | 1 | 1 | 2 | jane@example.com | Record Updated | 2 | 1 | 2 | joe@example.com | Record Deleted | 3 |
执行此查询会产生几乎相同的表:
SELECT * FROM Messages
GROUP BY Email
执行此查询会产生1条记录,我知道原因,但是我丢失了其他记录中的数据,例如Email,Message和ActionId:
SELECT * FROM Messages
GROUP BY RecordId
结果
Id | RecordId | Email | Message | ActionId | ---------------------------------------------------------------------- 1 | 2 | john@example.com | Record inserted | 1 |
无论如何,我可以Group By RecordId
仍然保留所有数据。我正在尝试根据RecordId
创建一条记录,同时保留所有数据,以便我可以向Email
列中的所有人发送一封电子邮件,但其各自的Message (Record Inserted, Record Deleted, Record Updated)
答案 0 :(得分:0)
GROUP_CONCAT()
会有帮助吗?
SELECT RecordId, GROUP_CONCAT(CONCAT_WS(",", Email, Message, ActionId) SEPARATOR ";")
FROM Messages GROUP BY RecordId
注意:GROUP_CONCAT()
结果长度限制。因此,如果您预见到将大量记录分组,那么它不是您的解决方案。
答案 1 :(得分:0)
以下查询将为每个RecordID返回一条记录,其中包含所有信息。 (这有点难看)
SELECT RecordId,
EMAIL = ( SELECT EMAIL + ';'
FROM Messages AS M
WHERE Messages.RecordId = M.RecordId
FOR XML PATH('')),
[Message] =(SELECT [Message] + ';'
FROM Messages AS M
WHERE Messages.RecordId = M.RecordId
FOR XML PATH('')),
ActionId =(SELECT ActionId + ';'
FROM Messages AS M
WHERE Messages.RecordId = M.RecordId
FOR XML PATH(''))
FROM Messages
GROUP BY RecordId