根据状态汇总货币列?

时间:2012-09-12 13:51:17

标签: mysql crosstab

我有一个交叉表查询,可以根据特定记录状态[活动,结束等]对所有记录进行很好的总结。

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

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

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

任何帮助都非常感激。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

SELECT
  c.ReferralName,
  CASE
    WHEN d.CaseStatusName = 'Active'
      THEN b.LeadCost
    ELSE 'SomethingElse'
  END AS casecolumn
...