左加入COUNT()

时间:2019-12-19 08:15:07

标签: tsql

我有以下查询,给我有关StatsStrategySessions表的第二个JOIN / COUNT的问题:

SELECT 
      fa.Id
    , CAST(fa.StatDate AS DATE)
    , COUNT(sa.CreatedDateTime) AS 'TotalApplications'
    , COUNT(ss.CreatedDateTime) AS 'TotalStrategySessions'
FROM StatsFacebookAds fa 
LEFT JOIN StatsApplications sa
ON CAST(fa.StatDate AS DATE) = CAST(sa.CreatedDateTime AS DATE)
AND sa.LeadSourceId = 1
LEFT JOIN StatsStrategySessions ss
ON CAST(fa.StatDate AS DATE) = CAST(ss.CreatedDateTime AS DATE)
AND ss.LeadSourceId = 1
GROUP BY      
      fa.Id
    , fa.StatDate

它返回的数量应该是它的两倍...

它返回...

  Id                     TotalApplications TotalStrategySessions
    ----------- ---------- ----------------- ---------------------
    1           2019-12-02 1                 1
    2           2019-12-03 0                 0
    3           2019-12-04 0                 0
    4           2019-12-05 4                 4

第二个JOIN / COUNT倍增至4,而不是原来的2。

当我在没有第二个JOIN / COUNT的情况下运行代码时,它会按预期返回。

代码按预期运行。

SELECT 
      fa.Id
    , CAST(fa.StatDate AS DATE)
    , COUNT(sa.CreatedDateTime) AS 'TotalApplications'
FROM StatsFacebookAds fa 
LEFT JOIN StatsApplications sa
ON CAST(fa.StatDate AS DATE) = CAST(sa.CreatedDateTime AS DATE)
AND sa.LeadSourceId = 1
GROUP BY      
      fa.Id
    , fa.StatDate

它返回我期望的...

Id                     TotalApplications
----------- ---------- -----------------
1           2019-12-02 1
2           2019-12-03 0
3           2019-12-04 0
4           2019-12-05 2

但是,一旦我加入第二张表,数字就不是我要显示的数字了。

自从我写了tsql以来已经有一段时间了,希望我能在它上面留一些...

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试在try { let fileName = require('../rar/myFile.zip'); console.log("file found"); } catch (e) { console.log("sorry, file not found"); } 表上使用不同的计数:

StatsApplications

这里的概念是,SELECT fa.Id, CAST(fa.StatDate AS DATE), COUNT(DISTINCT sa.CreatedDateTime) AS [TotalApplications], -- change is here COUNT(ss.CreatedDateTime) AS [TotalStrategySessions] FROM StatsFacebookAds fa LEFT JOIN StatsApplications sa ON CAST(fa.StatDate AS DATE) = CAST(sa.CreatedDateTime AS DATE) AND sa.LeadSourceId = 1 LEFT JOIN StatsStrategySessions ss ON CAST(fa.StatDate AS DATE) = CAST(ss.CreatedDateTime AS DATE) AND ss.LeadSourceId = 1 GROUP BY fa.Id, fa.StatDate; 表的第二个附加连接冒着复制StatsStrategySessions表中所有记录的风险,因为后面的每个记录可能都连接到前一个记录中的多个记录。但是,通过采用非重复计数,我们可以消除重复计数。

如果您不喜欢这种方法,那么处理此问题的另一种方法是在两个表上联接一个子查询,该子查询分别查找计数,然后联接回StatsApplications