1

我有一个交叉表查询,可以很好地根据某个记录状态汇总所有记录 [活动、结束等]

Select
  c.ReferralName,
  Sum((d.CaseStatusName) = 'Active') As Active,
  Sum((d.CaseStatusName) = 'Completed') As Completed,
  Sum((d.CaseStatusName) = 'Submitted') As Submitted,
  Count(b.CaseID) As Total,
  Sum(b.LeadCost) As Cost
From
  tblcontacts a Inner Join
  tblcases b On a.ContactID = b.ContactID Inner Join
  tblreferral c On c.RefferalID = a.ContactReferrelSource Inner Join
  tblcasestatus d On d.CaseStatusID = b.CaseStatusName
Group By
  c.ReferralName With Rollup

这很好用,但我现在还想运行一个查询,将 d.CaseStatusName 的总和替换为 b.LeadCost 的总和,但找不到实现它的方法!

我认为如果 d.CaseStatusName='Active' 等,我需要有 b.LeadCost 的总和等

非常感谢任何帮助。

4

2 回答 2

1
Select
  c.ReferralName,
  Sum(CASE WHEN (d.CaseStatusName) = 'Active'    THEN b.LeadCost ELSE 0 END) As Active,
  Sum(CASE WHEN (d.CaseStatusName) = 'Completed' THEN b.LeadCost ELSE 0 END) As Completed,
  Sum(CASE WHEN (d.CaseStatusName) = 'Submitted' THEN b.LeadCost ELSE 0 END) As Submitted,
  Count(b.CaseID) As Total,
  Sum(b.LeadCost) As Cost
From
  tblcontacts a Inner Join
  tblcases b On a.ContactID = b.ContactID Inner Join
  tblreferral c On c.RefferalID = a.ContactReferrelSource Inner Join
  tblcasestatus d On d.CaseStatusID = b.CaseStatusName
Group By
  c.ReferralName With Rollup
于 2012-09-12T14:12:49.757 回答
0

我不确定我是否理解您的要求,但似乎您可能希望CASE根据以下条件检查条件d.CaseStatusName

SELECT
  c.ReferralName,
  CASE
    WHEN d.CaseStatusName = 'Active'
      THEN b.LeadCost
    ELSE 'SomethingElse'
  END AS casecolumn
...
于 2012-09-12T14:11:25.163 回答