子查询通过绕过where子句

时间:2012-09-06 12:35:58

标签: mysql

早上好,mysql查询显示已完成日期字段的案例&总行数,我想针对总案例计算这个,但不确定我是否可以在一个查询中完成所有这些。例如,当前查询输出

Aug Sep Nov Total
10  20  20  50

的代码
     SELECT * from(
     Select Count(b.CaseID) As TotDB 
     from tblcontacts a 
     Inner Join  tblcases b 
     On a.ContactID = b.ContactAssignedTo)a
CROSS JOIN
    (Select
  Sum(Month(b.StatusSubmittedDate) = 8) As Aug,
  Sum(Month(b.StatusSubmittedDate) = 9) As Sep,
  Sum(Month(b.StatusSubmittedDate) = 10) As Oct,
  Count(b.CaseID) As Total,
  ROUND (100*Count(b.CaseID)/Count(b.CaseID),2) As Conversion
From
  tblcontacts a Inner Join
  tblcases b On a.ContactID = b.ContactAssignedTo
Where
  b.StatusSubmittedDate > '2012 - 01 - 01'
Group By
  a.ContactFullName With Rollup
Having
  Sum(b.CaseCommission) > 0.01)b 

我需要输出的是下面的内容,所以我在上面添加了TotDB行,看看是否会有所帮助,但事实并非如此。我需要知道的是,我可以在此查询中有一个列绕过where / having子句来显示所有记录

Aug Sep Nov Tot TotDB %Converted
10  20  20  50  100   50%

由于

2 个答案:

答案 0 :(得分:1)

可能你应该这样做:

select Aug,Sep, Nov, Tot,TotDB,(Tot/TotDB*1.0)*100 as '%Converted' 
 from 
(SELECT * from(
     Select Count(b.CaseDate) As TotDB 
     from tblcontacts a 
     Inner Join  tblcases b 
     On a.ContactID = b.ContactAssignedTo)a
CROSS JOIN
    (select  
      Sum(Month(b.StatusSubmittedDate) = 9) As Sep,
      Sum(Month(b.StatusSubmittedDate) = 10) As Oct,
      Sum(Month(b.StatusSubmittedDate) = 11) As Nov,
      Count(b.CaseID) As Total,
    From tblcontacts a 
    Inner Join tblcases b 
    On a.ContactID = b.ContactAssignedTo
    Where
      b.StatusSubmittedDate > '2012-01-01'
    Group By
      a.ContactFullName With Rollup
    Having
      Sum(b.CaseCommission) > 0.01)b)c

答案 1 :(得分:0)

您不能在一个简单的查询中执行此操作。

正确的方法是在没有where子句的情况下进行第二次查询。真。

如果您必须在一个查询中执行此操作,则至少使用union:

/* old query */
SELECT a,b,c from t1,t2,t3 where d=e group by a having b>f
UNION
select 'total',COUNT(*),NULL /*need the same amount of rows*/
from t1,t2,t3 

让您的客户以不同的方式对待a='total'行。但这是一个黑客。我建议你使用两个查询。