Name Wage Year
John 25,000 2016
John 35,000 2016
John 50,000 2015
Paul 70,000 2015
Paul 72,000 2016
George 50,000 2015
George 50,000 2016
假设我有上述SQL表,我如何比较一年只有一个工资的个人与有多个工资的个人的平均工资?例如。 2016年,一个工资的人比一个人的工资收入多,反之亦然?
我试图写一个只出现一年一次的人与那些出现不止一次的人的查询,并比较两组的平均工资。
我想要的结果是:
single_wage_average multiple_wage_average Year
50,000 61,000 2016
答案 0 :(得分:1)
您可以使用平均值获得所有这些并计算如下:
select *, AverageWage = avg(wage) over(partition by name, [year]),
[CountOfOneWage]=count(name) over(partition by name, [year]) from #yourwage
order by name
使用此查询,您可以获得所需的输出。
您的输入表:
create table #yourwage (name varchar(20), wage money, year int)
insert into #yourwage
( Name , Wage , [Year] ) values
('John', 25000 , 2016 )
,('John', 35000 , 2016 )
,('John', 50000 , 2015 )
,('Paul', 70000 , 2015 )
,('Paul', 72000 , 2016 )
,('George', 50000 , 2015 )
,('George', 50000 , 2016 )
答案 1 :(得分:0)
我将从聚合开始:
select name, year, avg(wage) as avg_wage, count(*) as num
from t
group by name, year;
然后你可以再次聚合:
select year,
avg(case when num = 1 then avg_wage end) as singleton_avg,
avg(case when num > 1 then avg_wage end) as duplicate_avg
from (select name, year, avg(wage) as avg_wage, count(*) as num
from t
group by name, year
) ny
group by year;