sql查询实现两个计数在一个

时间:2011-03-22 09:20:57

标签: mysql sql count pivot

SELECT (select count(u.ag_code) 
from table1 as u inner join table2 as tc 
on u.industry_id=tc.tempcatid 
where u.ag_code!=0) as agnt,
    (select count(u.ag_code) 
     from table1 as u inner join table2 as tc 
     on u.industry_id=tc.tempcatid where u.ag_code=0),as dircus,
tc.catename from table1 as u inner join table2 as tc 
where u.industry_id=tc.tempcatid 
group by tc.tempcatid

此查询有错误 我在一个查询中需要两个计数和类别名称 这是计数的条件

  1. ag_code!= 0
  2. ag_code = 0
  3. table1中的

    具有列ag_code(它具有0和非零值)

    我的结果需要像这样

    Full Texts
    agent   customer    catename
    11  3   Real Estate
    15  1   Automobile
    3   0   Medical
    34  77  Business
    1   45  Travel & Hotels
    11  3   Construction & Engineering
    

2 个答案:

答案 0 :(得分:1)

SELECT tc.catename,
       count(case when u.ag_code!=0 then 1 end) agnt,
       count(case when u.ag_code =0 then 1 end) dircus
from table1 as u
inner join table2 as tc on u.industry_id=tc.tempcatid 
group by tc.tempcatid, tc.catename

答案 1 :(得分:0)

您好,您可以使用以下示例来获取所需的结果。

Select SUM(Inactive) Inactive ,SUM(Active) Active FROM
( 
    Select Count(t1.UserId) Inactive,0 Active 
    FROM
    (select * from users where inactive=1) as t1
    UNION 
    SELECT 0 Inactive,Count(t2.UserId) Active  FROM
    (select * from users where inactive=0) as t2  
) as result
相关问题