在这种情况下,如何仅减少一个SQL查询 [英] How to reduce SQL queries in only one in this case

查看:111
本文介绍了在这种情况下,如何仅减少一个SQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一张这样的表:

 姓名,年龄
{
Mike,7
Peter,2
Mario,1
Tony,4
Mary,2
Tom,7
Jerry,3
Nick,2
Albert,22
Steven,7
}

我想得到以下结果:

 结果(custom_text,num)
{
1年,1
2年,3
3年,1
4年,1
5年,0
6年,0
7年,3
8年,0
9年,0
10年,0
超过10年,1
}

我知道如何做到这一点,但在11查询:(但如何简化它?)



编辑: 以下是我可以获得的非零值,但我需要在正确的位置零。

  SELECT COUNT(*)ASAgeCount 
FROM mytable
GROUP BY年龄

我该如何做到这一点?
感谢您阅读。

解决方案

您可以使用下面的查询,但它不会显示差距如果你想要差距,那么使用 Linoff的回答

 
中选择t.txt,count(t.age)(年龄<11时选择
case
然后concat(年龄,'year')
else'超过10'
结束txt,从your_table中扣除
)t
t.txt
order by 1

SQL FIDDLE DEMO


I want to save the hassle of doing many querys for the following:

I have a table like this:

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

And I want the following result:

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
}

I know how to do this but in 11 queries :( But how to simplify it?

EDIT:

Doing the following, I can obtain the non zero values, but I need the zeroes in the right places.

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

How can I achieve this? Thanks for reading.

解决方案

you can use below query but it will not show the gaps if you want gaps then the use 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

这篇关于在这种情况下,如何仅减少一个SQL查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆