我有一个表数据库,包含以下字段: 身份证,资历(年),结果和其他一些不太重要的领域。 表行示例:
ID:36 Seniority(years):1.79 outcome:9627
我需要用相对简单的代码编写一个查询(sql server),返回平均结果,按资历字段分组,五年(0-5岁,6-10等等)的跳跃与条件是只有当组有超过3行时才会显示平均值。
结果行示例:
range:0-5 average:xxxx
非常感谢
答案 0 :(得分:1)
使用select floor(seniority / 5), avg(outcome)
from t
group by floor(seniority / 5)
having count(*) >= 3;
语句创建不同的年龄组。试试这个
CASE
由于您有小数位,如果您想将select case when Seniority between 0 and 5 then '0-5'
when Seniority between 6 and 10 then '6-10'
..
End,
Avg(outcome)
From yourtable
Group by case when Seniority between 0 and 5 then '0-5'
when Seniority between 6 and 10 then '6-10'
..
End
Having count(1)>=3
计入5.4
组而0-5
计为5.6
,请使用6-10
代替{{1}在Round(Seniority,0)
语句
答案 1 :(得分:0)
这就像是:
return redirect()->action('GuardianAuth\LoginController@login')->withInput();
注意:这会将资历分成相等大小的组,即0-4,5-9等等。这似乎比拥有不平等群体更合理。
答案 2 :(得分:0)
你可以按照 Gordon 的回答(但你应该稍微编辑一下),但是我会用额外的表格来做所有可能的间隔。然后,您可以添加适当的索引来提升它。
create table intervals
(
id int identity(1, 1),
start int,
end int
)
insert into intervals values
(0, 5),
(6, 10)
...
select i.id, avg(t.outcome) as outcome
from intervals i
join tablename t on t.seniority between i.start and i.end
group by i.id
having count(*) >=3
如果无法创建新表,则可以始终使用CTE
:
;with intervals as(
select * from
(values
(0, 5),
(6, 10)
--...
) t(start, [end])
)
select i.id, avg(t.outcome) as outcome
from intervals i
join tablename t on t.seniority between i.start and i.[end]
group by i.id
having count(*) >=3
答案 3 :(得分:0)
P.S。 0-5包含6个值,而6-10包含5.
select 'range:'
+ cast (isnull(nullif(floor((abs(seniority-1))/5)*5+1,1),0) as varchar)
+ '-'
+ cast ((floor((abs(seniority-1))/5)+1)*5 as varchar) as seniority_group
,avg(outcome)
from t
group by floor((abs(seniority-1))/5)
having count(*) >= 3
;