SQL-запрос реализует два счета в одном - PullRequest
1 голос
/ 22 марта 2011
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

в таблице1 есть столбец 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 ]

1 голос
/ 22 марта 2011
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
0 голосов
/ 22 марта 2011

Привет. Возможно, вы сможете использовать приведенный ниже пример, чтобы получить нужный вам результат.

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
...