在这种情况下,如何仅在一个中减少SQL查询

时间:2015-03-29 23:57:55

标签: mysql sql join group-by having

我想省去为以下事情做许多查询的麻烦:

我有一张这样的表:

name, age
{
    Mike, 7
    Peter, 2
    Mario, 1
    Tony, 4
    Mary, 2
    Tom, 7
    Jerry, 3
    Nick, 2
    Albert, 22
    Steven, 7
}

我想要以下结果:

Results(custom_text, num)
{
    1 Year, 1
    2 Year, 3
    3 Year, 1
    4 Year, 1
    5 Year, 0
    6 Year, 0
    7 Year, 3
    8 Year, 0
    9 Year, 0
    10 Year, 0
    More than 10 Year, 1
}

我知道怎么做但是在11个查询中:(但是如何简化呢?

修改

执行以下操作,我可以获得非零值,但我需要在正确的位置使用零。

SELECT COUNT(*) AS AgeCount
FROM mytable
GROUP BY Age

我怎样才能做到这一点? 谢谢你的阅读。

3 个答案:

答案 0 :(得分:2)

您可以使用left join和子查询来获得所需内容:

select coalesce(concat(ages.n, ' year'), 'More than 10 year') as custom_text,
       count(*)
from (select 1 as n union all select 2 union all select 3 union all select 4 union all
      select 5 union all select 6 union all select 7 union all select 8 union all
      select 9 union all select 10 union all select null
     ) ages left join
     tabla t
     on (t.age = ages.n or ages.n is null and t.age > 10)
group by ages.n;

编辑:

我认为以下是进行此查询的更好方法:

select (case when least(age, 11) = 11 then 'More than 10 year'
             else concat(age, ' year')
        end) as agegroup, count(name)
from (select 1 as age, NULL as name union all
      select 2, NULL union all
      select 3, NULL union all
      select 4, NULL union all
      select 5, NULL union all 
      select 6, NULL union all
      select 7, NULL union all
      select 8, NULL union all
      select 9, NULL union all
      select 10, NULL union all
      select 11, NULL 
      union all
      select age, name
      from tabla t
     ) t
group by least(age, 11);

基本上,查询需要full outer join而MySQL不提供。{但是,我们可以通过为每个年龄添加额外的值来获得相同的结果,因此我们知道有些东西存在。然后,由于nameNULLcount(name)将为这些行返回0

答案 1 :(得分:2)

您可以使用以下查询,但如果您需要差距will not show the gaps,请使用Linoff's answer

select t.txt, count(t.age) from 
(select 
  case 
      when age<11 then concat(age ,' year') 
      else 'more than 10' 
  end txt, age
from your_table)t
group by t.txt
order by 1

SQL FIDDLE DEMO

答案 2 :(得分:0)

请尝试将此查询用于所需的输出。 SQL FIDDLE链接http://www.sqlfiddle.com/#!9/4e52a/6

X = data(:,4:end)
[a,~,x] = unique(X(~strcmp(X,'')))
occ = hist(x(:),1:numel(a))
out = [a num2cell(occ).']