根据特定条件SQL计算值

时间:2017-01-15 04:36:58

标签: sql sql-server

我正在尝试为我们的CRM计划中的某些报告撰写一个视图,而我在计算方面遇到了问题。我们正在尝试根据特定条件计算推荐数量。我觉得我写这个视图的方式不正确。我试图使用CASE语句来确保它计算我想要的值,但是我得到的数字我无法通过逆向工程验证。

我是否正确构建了CASE语句?

(注意:我确实意识到客户端拼写错误,不幸的是,在我获得数据库之前编写数据库的人有一些拼写问题。)

这是我到目前为止所写的:

SELECT Comp_Name, Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Client' Then 1
                        ELSE NULL END) AS Client_Referrals,
      Count(Case WHEN lead_companyprimaryreferralsource IS NOT NULL Then 1 Else Null End) AS Target_Referrals,
      Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Prospect' Then 1 Else Null End) As Prospective_Client_Referral, 
      Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Lost_Clent' Then 1 Else Null End) AS Lost_Client_Referral,
      Count(Case WHEN mcgr_companyid IS NOT NULL Then 1 Else NULL END) AS Intro_By_MCG

FROM Company

RIGHT JOIN Lead on Lead_PrimaryCompanyID = Comp_CompanyId
RIGHT JOIN MCGRelationships on mcgr_companyid = Comp_CompanyId
WHERE COMP_Name IS NOT NULL

Group By Comp_Name

以下是我得到的样本:

  Client1      0    0   0   0   1
  Client2      0    0   0   0   2
  Client3      0    0   0   0   1
  Client4      0    0   0   0   1
  Client5      0    0   0   0   2
  Client6      0    0   0   0   2
  Client7      0    0   4   0   4
  Client8      0    0   0   0   2
  Client9      0    2   2   0   2
  Client10     12   6   0   0   12
  Client11     0    0   0   0   2

当我在客户端10是主要推荐源的表上运行查询时,我什么也得不到。所以我无法解释这12个实例。

1 个答案:

答案 0 :(得分:0)

如果每个公司记录可以有多个关系记录,我认为您的问题可能在于加入MCGRelationships。如果我正确地关注了您,那么如果该记录存​​在于MCGRelationships中,您希望Intro_By_MCG为1,无论其出现的次数如何。通过加入表格,您的查询将计算与领导者所来自的公司相关联的每个MCGRelationship的一次。试试这个,如果结果不同,请告诉我们:

SELECT Comp_Name, Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Client' Then 1
                    ELSE NULL END) AS Client_Referrals,
  Count(Case WHEN lead_companyprimaryreferralsource IS NOT NULL Then 1 Else Null End) AS Target_Referrals,
  Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Prospect' Then 1 Else Null End) As Prospective_Client_Referral, 
  Count(Case WHEN comp_primaryreferralsource IS NOT NULL and Comp_type = 'Lost_Clent' Then 1 Else Null End) AS Lost_Client_Referral,
  Count(Case WHEN EXISTS (Select Comp_CompanyId FROM MCGRelationships WHERE mcgr_companyid = Comp_CompanyId) Then 1 Else NULL END) AS Intro_By_MCG

FROM Company

RIGHT JOIN Lead on Lead_PrimaryCompanyID = Comp_CompanyId
WHERE COMP_Name IS NOT NULL

Group By Comp_Name