SQL多个来自多个表的计数

时间:2016-06-16 13:52:21

标签: sql sql-server sql-server-2005

我有以下表(“All_Countries” & “_Sent”),需要获得“Result”表中显示的结果。我想要的是计算所有“SubscriberKeys”和连接到这些SubscriberKeys的总“SendIDs”,按“Source”分组 - 就像在“Result”表中一样。我设法通过使用下面的查询实现了这个(我认为),但我不确定我是否以错误的方式做到了。没有更好(更有效)的方法只使用一个select语句并且没有额外的子查询吗?我使用的是SQL Server 2005。

All_Countries

-------------------------------
SubscriberKey*    | Source
-------------------------------
10001             | Campaign1
10002             | Campaign2
10003             | Campaign1

_Sent

-----------------------
SendID*| SubscriberKey*
-----------------------
1      | 10001
2      | 10001
3      | 10002
4      | 10002
5      | 10003
6      | 10003

结果

-----------------------------------------------------
Source*          | SubscriberCount       | SendCount
-----------------------------------------------------
Campaign1        | 2                     | 4
Campaign2        | 1                     | 2


  

主键= *(例如,列中有星号的地方)

SELECT a.Source, COUNT(a.SubscriberKey) AS Subscribers, 
(SELECT COUNT(b.SubscriberKey) AS Sent FROM _Sent AS b
INNER JOIN All_Countries AS c ON b.SubscriberKey = c.SubscriberKey
WHERE c.Source = a.Source) AS Sent
FROM All_Countries AS a
GROUP BY a.Source

3 个答案:

答案 0 :(得分:1)

我还没有对此进行测试,但我认为您可以在第一个COUNT

中使用DISTINCT关键字获得所需内容
SELECT
    c.Source,
    COUNT(DISTINCT SubscriberKey) AS SubscriberCount,
    COUNT(*) AS SendCount
FROM
    All_Countries c
        JOIN _Sent s ON s.SubscriberKey = c.SubscriberKey 
GROUP BY
    c.Source

答案 1 :(得分:0)

这样的查询怎么样?

select 
    source, count(distinct a.SubscriberKey) as SubscriberCount, count(distinct b.SendID) as SendCount
from All_Countries a join 
     _Sent b ON a.SubscriberKey = b.SubscriberKey

答案 2 :(得分:0)

SELECT  [Source],
        COUNT(DISTINCT a.SubscriberKey) as SubscriberCount,
        COUNT(SendId) as SendCount
FROM All_Countries a
INNER JOIN _Sent s 
    ON s.SubscriberKey = a.SubscriberKey
GROUP BY [Source]

输出:

Source      SubscriberCount SendCount
Campaign1   2               4
Campaign2   1               2