假设我有一个以下查询(我的实际查询的一部分),它检索该人的person_id和年龄:
select p.person_id,TRUNC ((SYSDATE - p.birth_date) / 365.25, 0) AS age
from person p
现在,在达到这个年龄后,我希望得到每个年龄段的人数,如:
group count
age <=5 100
age >5 and age <=10 50
age > 10 15
... ...
我可以使用group by子句来计算个人年龄。但如何在两个年龄之间计算?
有人可以告诉我我可以这样做的方式吗?
您可以使用以下数据供您参考:
pid age
1 4
2 13
3 10
4 8
5 9
6 12
所以结果应该是:
group count
age < =5 1
>5 & <=10 3
> 10 2
答案 0 :(得分:3)
首先,您的年龄计算不正确。你几乎肯定想要测量两个日期之间的月份,而不是希望除以365.25足够接近
trunc( months_between( sysdate, p.birth_date )/ 12 )
其次,如果您想按范围分组,您只需要在case
语句中选择范围并按
SELECT (case when age <= 5
then 'age <= 5'
when age > 5 and age <= 10
then 'age > 5 and age <= 10'
else 'age > 10'
end) bucket,
count(*)
FROM( SELECT trunc( months_between( sysdate, p.birth_date )/ 12 ) age
FROM person p )
GROUP BY (case when age <= 5
then 'age <= 5'
when age > 5 and age <= 10
then 'age > 5 and age <= 10'
else 'age > 10'
end)
答案 1 :(得分:1)
假设您已经有年龄的计算值。您可以使用 CASE 表达式和 GROUP BY 不同年龄段。
例如,
SQL> WITH data(person_id, age) AS(
2 SELECT 1, 3 FROM dual UNION ALL
3 SELECT 2, 4 FROM dual UNION ALL
4 SELECT 3, 8 FROM dual UNION ALL
5 SELECT 4, 9 FROM dual UNION ALL
6 SELECT 5, 15 FROM dual UNION ALL
7 SELECT 6, 25 FROM dual UNION ALL
8 SELECT 7, 32 FROM dual UNION ALL
9 SELECT 8, 44 FROM dual UNION ALL
10 SELECT 9, 67 FROM dual UNION ALL
11 SELECT 10, 75 FROM dual
12 )
13 SELECT (
14 CASE
15 WHEN age <= 5
16 THEN 'age <= 5'
17 WHEN age > 5 AND age <= 10
18 THEN 'age > 5 and age <= 10'
19 WHEN age > 10 AND age <= 30
20 THEN 'age > 10 and age <= 30'
21 ELSE 'age > 30'
22 END) age_group,
23 COUNT(*)
24 FROM data
25 GROUP BY (
26 CASE
27 WHEN age <= 5
28 THEN 'age <= 5'
29 WHEN age > 5 AND age <= 10
30 THEN 'age > 5 and age <= 10'
31 WHEN age > 10 AND age <= 30
32 THEN 'age > 10 and age <= 30'
33 ELSE 'age > 30'
34 END)
35 /
AGE_GROUP COUNT(*)
---------------------- ----------
age <= 5 2
age > 10 and age <= 30 2
age > 5 and age <= 10 2
age > 30 4
SQL>
如果您没有年龄范围,则可以使用解码对确切年龄进行硬编码。
答案 2 :(得分:1)
您可能想要这样做:
dot_prod_total = sum(np.outer(cell[key], patient[key]).flat for key in cell)
dot_prod_total =
Pat_1&LN18 Pat_1&22RV1 Pat_1&DU145 Pat_2&LN18 ...
8 10 12 16