查询数据库以按唯一标识获取数据

时间:2019-06-20 20:55:27

标签: sql sql-server

我有一个数据库表,其中包含以下信息(不要介意CreatedDates不匹配,这是一个测试数据库表):

enter image description here

我希望能够基于Intents(一个用户有多个)对Transcript和相应的ContactId创建查询。

截至目前,我已经能够完成以下操作,按用户(不同)拉出Intents

SELECT distinct [ContactId],[Intents] = 
    STUFF((SELECT ' ,' + LTRIM(RTRIM(Intent))
           FROM ACCOUNT_DATA b
           WHERE b.ContactId = a.ContactId
          FOR XML PATH('')), 1, 2, '')
FROM ACCOUNT_DATA a
GROUP BY ContactId;

我想要的输出将是这样的:

查询=>从数据库中选择所有用户(不同),然后返回意图(不同)+脚本数据和意图计数。就像这样:

d463d996-78cc-428e-8a76-e4875e1c8ff4
RescheudleApt (4) : Reschuedle Appointment, Ok, what date?, Ok, what date?,Ok, what date?
ConfirmAppt (2): Confirm my appointment, ok your appointment has been confirmed

对于表中的每个ContactId,依此类推,我将如何处理?我走在正确的轨道上吗?

我知道这会在不同的别名表中格式化,例如ContactIdCountTranscript

1 个答案:

答案 0 :(得分:0)

尝试像这样更改查询:

SELECT 
    ContactId,
    Intent + ' (' + CONVERT(VARCHAR,COUNT(Intent)) + ')' as Intents, 
    [Transcript] = STUFF((SELECT ' ,' + LTRIM(RTRIM(b.Transcript))
                          FROM ACCOUNT_DATA b
                          WHERE b.ContactId = a.ContactId
                            AND b.Intent = a.Intent
                          FOR XML PATH('')), 1, 2, '')
FROM 
    ACCOUNT_DATA a
GROUP BY 
    ContactId, Intent
ORDER BY 
    ContactId

这里是demo

或者如果您想串联IntentTranscript

SELECT 
    ContactId,
    Intent + ' (' + CONVERT(VARCHAR,COUNT(Intent)) + ') : ' +
        STUFF((SELECT ' ,' + LTRIM(RTRIM(b.Transcript))
               FROM ACCOUNT_DATA b
               WHERE b.ContactId = a.ContactId
                 AND b.Intent = a.Intent
               FOR XML PATH('')), 1, 2, '') AS "Intent + Transcript"
FROM
    ACCOUNT_DATA a
GROUP BY 
    ContactId, Intent
ORDER BY 
    ContactId

编辑:最终查询

SELECT DISTINCT ContactId, [Transcript]=STUFF((SELECT '; ' + IntentTranscript
           FROM (
                    SELECT a.ContactId,
                        a.Intent + ' (' + CONVERT(VARCHAR,COUNT(a.Intent)) + ') : ' +
                        STUFF((SELECT ' ,' + LTRIM(RTRIM(b.Transcript))
                               FROM ACCOUNT_DATA b
                               WHERE b.ContactId = a.ContactId
                               AND b.Intent = a.Intent
                              FOR XML PATH('')), 1, 2, '') AS "IntentTranscript"
                    FROM ACCOUNT_DATA a
                    GROUP BY a.ContactId, a.Intent
                ) c
           WHERE c.ContactId = INNER_ACCOUNT_DATA.ContactId
          FOR XML PATH('')), 1, 2, '')
FROM 
(
    SELECT a.ContactId,
        a.Intent + ' (' + CONVERT(VARCHAR,COUNT(a.Intent)) + ') : ' +
        STUFF((SELECT ' ,' + LTRIM(RTRIM(b.Transcript))
               FROM ACCOUNT_DATA b
               WHERE b.ContactId = a.ContactId
               AND b.Intent = a.Intent
              FOR XML PATH('')), 1, 2, '') AS "IntentTranscript"
    FROM ACCOUNT_DATA a
    GROUP BY a.ContactId, a.Intent
) AS INNER_ACCOUNT_DATA
ORDER BY ContactId

这里是demo