首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在SQL中通过绑定进行计数

如何在SQL中通过绑定进行计数
EN

Stack Overflow用户
提问于 2019-09-21 05:05:23
回答 1查看 860关注 0票数 0

我有一些样本数据

代码语言:javascript
运行
复制
age year  score
0  2018    10
7  2019    20
11 2018    30
13 2019    40
14 2018    50

我想像

代码语言:javascript
运行
复制
count       
       year 
age    2018  2019
0-4     1     0
5-9     0     1
10-14   2     1
15-19   0     0

我想总结一下

代码语言:javascript
运行
复制
total score      
       year 
age    2018  2019
0-4     10    0
5-9     0     20
10-14   80    40
15-19   0     0

我tried.but它不能很好地工作,后来我尝试通过电子表格旋转。

如何使用SQL进行上述转换?

EN

回答 1

Stack Overflow用户

发布于 2019-09-21 06:30:36

一种方法是利用整数数学将年龄转化为他们的“年龄组”。7/5是1)。然后使用case语句创建2018和2019列。

代码语言:javascript
运行
复制
select
  age/5*5 as age_group_lower,
  case year
  when 2018 then
    score
  end as "2018",
  case year
  when 2019 then
    score
  end as "2019"
from scores;

age_group_lower  2018  2019
0                10     
5                      20
10               30     
10                     40
10               50     

这可以在CTE中使用,并根据您的喜好进行汇总。

代码语言:javascript
运行
复制
with score_years as (
    select
      age/5*5 as age_group_lower,
      case year
      when 2018 then
        score
      end as "2018",
      case year
      when 2019 then
        score
      end as "2019"
    from scores
)
select
  age_group_lower || '-' || age_group_lower + 4 as age_group,
  sum("2018") as "2018", sum("2019") as "2019"
from score_years
group by age_group_lower
order by age_group_lower;

age_group   2018    2019
0-4         10  
5-9                 20
10-14       80      40

这是Postgres语法(抱歉,我不知道Oracle),但是这里没有什么是Oracle不能处理的。

[医]小提琴

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58037424

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档