我有一个包含客户详细信息的表“客户”和一个存储每个电话结果的表“呼叫”
当我需要获取必须致电的客户列表时,我会使用此查询
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 以更简单和更好的方式完成
可以建议方向吗?
谢谢