【问题标题】:sql query implement two count in onesql查询实现二合一
【发布时间】:2011-03-22 09:20:56
【问题描述】:
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

在 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

【问题讨论】:

  • 问题是什么?您发布的查询有什么结果?
  • 我真的试图专注于您的查询到底在做什么,但我真的无法掌握它。您需要在此处更详细地描述您要完成的工作。

标签: mysql sql count pivot


【解决方案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

【讨论】:

  • 感谢它提供了我预期的结果
  • @mohan - 太棒了!请在答案旁边打勾 - 再过几分钟你就不能这样做了
  • 是明确声明“else NULL”还是保持简短但隐含(因此并不总是被理解)更好?
  • @Dems:有两种中间方式,例如:保持简短并解释其含义保持简短并让其他人解释其含义。 :)
  • 您好,我之前需要相同的查询,但计数需要 mcgross 列基于 2 种条件类型 1.ag_code=0 2.ag_code!=0 SELECT tc.catename, count(case mcgross when u. ag_code!=0 then 1 end) agnt, count(case mcgross 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 我需要根据 2 条件 1.ag_code=0 2.ag_code!=0 计算 mcgross
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多