Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL从多个表中进行多次计数_Sql_Sql Server_Sql Server 2005 - Fatal编程技术网

SQL从多个表中进行多次计数

SQL从多个表中进行多次计数,sql,sql-server,sql-server-2005,Sql,Sql Server,Sql Server 2005,我有以下表格(“所有国家”和“已发送”),需要获得“结果”表格中显示的结果。我想要的是计算所有“SubscriberKeys”和连接到这些SubscriberKeys的总的“SendIDs”,按“Source”分组–就像在“Result”表中一样。我(我想)通过使用下面的查询实现了这一点,但我不确定我是否用了错误的方法。有没有更好(更有效)的方法只使用一条select语句而不使用额外的子查询?我使用SQLServer2005 所有国家 ------------------------------

我有以下表格
(“所有国家”和“已发送”)
,需要获得
“结果”
表格中显示的结果。我想要的是计算所有“SubscriberKeys”和连接到这些SubscriberKeys的总的
“SendIDs”
,按
“Source”
分组–就像在
“Result”
表中一样。我(我想)通过使用下面的查询实现了这一点,但我不确定我是否用了错误的方法。有没有更好(更有效)的方法只使用一条select语句而不使用额外的子查询?我使用SQLServer2005

所有国家

-------------------------------
SubscriberKey*    | Source
-------------------------------
10001             | Campaign1
10002             | Campaign2
10003             | Campaign1
_发送

结果

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

主键=*(例如,列中有一个星号)


我还没有测试过这个,但是我认为你可以通过在你的第一个页面中使用DISTINCT关键字来得到你想要的


这样的查询怎么样

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
输出:

Source      SubscriberCount SendCount
Campaign1   2               4
Campaign2   1               2

使用
ctrl-K
将其格式化为代码,而不需要插入html来格式化空格。您好@simon-g interest将是我想说的最好的…谢谢您的提示@JuanCarlosOropeza!我在这里有点新手:)
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
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
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