如何从SQL中的不同记录中获取平均值

时间:2017-12-19 17:21:11

标签: sql sql-server average

假设我有两张桌子:

table1和table2

**Table1**

'MusicGenres'
------------
Pop
Techno
Trance
trap
Hardcore
Electro


**Table2**

'SongID'       'MusicGenres'
 ----------------------------
 1        |     Hardcore
 2        |     Hardcore
 3        |     Pop
 4        |     Trap
 5        |     Hardcore
 6        |     Pop
 7        |     Electro
 8        |     Electro
 9        |     Pop
 10       |     Pop
 11       |     Pop

结果我想要这样的东西:

Pop     20% of total
Techno  0% of total
Trance  0% of total
trap    5% of total
Hardcore  40% of totl
Electro  55% of total

我希望你们能帮助我搞清楚。我尝试了多种方法,但无法找到答案。

4 个答案:

答案 0 :(得分:2)

Select MusicGenres, 
       (100.0 * Count(*) / (Select Count(*) From Table2)) as percentage
From Table2
Group By MusicGenres

答案 1 :(得分:0)

这样的事情应该有效。

declare @Total int = (select count(*) from Table2);

select  t2.MusicGenre
        , 100.0*count(*)/@Total as [% of Total]
from    Table2 t2
group 
by      t2.MusicGenre

答案 2 :(得分:0)

你可以试试这个:

SELECT t1.MusicGenres + ' ' + CONVERT(NVARCHAR(200), COUNT(*) * 100 / (SELECT COUNT(*) FROM Table2)) + '% of total'
FROM Table1 t1 LEFT OUTER JOIN Table2 t2
ON t1.MusicGenres = t2.MusicGenres
GROUP BY t1.MusicGenres

答案 3 :(得分:0)

尝试以下方法:

declare @tab1 table (MusicGenres varchar(10))
insert into @tab1
select 'Pop' union all
select 'Techno' union all
select 'Trance' union all
select 'trap' union all
select 'Hardcore' union all
select 'Electro'

declare @tab2 table (SongID  int, MusicGenres varchar(10))
 insert into @tab2
 select 1        ,'Hardcore' union all
 select 2        ,'Hardcore' union all
 select 3        ,'Pop' union all
 select 4        ,'Trap' union all
 select 5        ,'Hardcore' union all
 select 6        ,'Pop' union all
 select 7        ,'Electro' union all
 select 8        ,'Electro' union all
 select 9        ,'Pop' union all
 select 10       ,'Pop' union all
 select 11       ,'Pop'

declare @Total int = (select count(*) from @tab2);

select  t1.MusicGenres, convert(varchar(5), cast(SUM(case when t2.SongID is not null then 1 else 0 end) *100.0/(select count(*) from @tab2) as numeric(5,2))) + '% of Total' as Share
from    @tab1 t1
left join @tab2 t2 on t1.MusicGenres = t2.MusicGenres
group by  t1.MusicGenres 

感谢。