SQL Server 2012合并OUUT APPLY相关表中的记录

时间:2017-02-16 08:39:15

标签: sql-server-2012 outer-apply

我有一张桌子"客户"与客户的详细信息和表" CALLS"我存储每个电话的结果

当我需要获取我必须呼叫的客户列表时,我使用此查询

SELECT *
FROM (
    SELECT TOP (50) S.ID,S.URL,S.Phone,S.Email
    FROM dbo.Customers AS S
    WHERE URL is not null and City like 'Berl%'
    ORDER BY S.ID 
    ) AS S

OUTER APPLY (
SELECT TOP (3) I.CalledOn, I.Answer
FROM dbo.Calls AS I
WHERE S.URL = I.URL
ORDER BY I.CalledOn DESC
) AS I;

我获取了该城市所有客户的列表以及最后3个答案。

但是每个客户最多返回3条记录,而我只有一条记录 并将CalledOn和Answer的值3汇总到同一记录中

更清楚: 现在:

+-----------+---------------+-------------+------------------+
|Customer 1 |  555-333 333  | 02-10-17    | Call Tomorrow    |
+-----------+---------------+-------------+------------------+
|Customer 2 |  555-444 333  | 02-10-17    | Call Tomorrow    |
+-----------+---------------+-------------+------------------+
|Customer 1 |  555-333 333  | 02-11-17    | Call Tomorrow    |
+-----------+---------------+-------------+------------------+
|Customer 1 |  555-333 333  | 02-12-17    | Stop Calling     |
+-----------+---------------+-------------+------------------+

预期

+-----------+---------------+--------------------------------+
|Customer 1 |  555-333 333  | 02-12-17 : Call Stop Calling   |
|           |               | 02-11-17 : Call Tomorrow       |
|           |               | 02-10-17 : Call Tomorrow       |
+-----------+---------------+-------------+------------------+
|Customer 2 |  555-444 333  | 02-10-17    | Call Tomorrow    |
+-----------+---------------+-------------+------------------+

目前,我已经通过服务器端逻辑实现了这一目标,但我确信它可以通过TSQL更轻松,更好地实现

可以建议方向吗?

由于

1 个答案:

答案 0 :(得分:1)

对于SQL-Server 2012

SELECT TOP (50) S.ID, S.URL, S.Phone, S.Email,
           STUFF((SELECT CHAR(10) + concat (I.CalledOn, ' ', I.Answer)
                  FROM dbo.Calls AS I
                  WHERE S.URL = I.URL
                  ORDER BY I.CalledOn DESC
                  FOR XML PATH('')
                ), 1, 1, '') AS CallAnswer
FROM dbo.Customers AS S
WHERE URL is not null and City like 'Berl%'
ORDER BY S.ID 

vNext:

SELECT TOP (50) S.ID, S.URL, S.Phone, S.Email,
           (SELECT TOP (3) STRING_AGG(CONCAT(I.CalledOn, ' ', I.Answer), CHAR(13))
            FROM dbo.Calls AS I
            WHERE S.URL = I.URL
            ORDER BY I.CalledOn DESC
           ) AS CallAnswer
FROM dbo.Customers AS S
WHERE URL is not null and City like 'Berl%'
ORDER BY S.ID 

在此处查看:http://rextester.com/HSIEL20631