2017-08-09 34 views
1

我有兩個表:表A有多少百分比的數據來自表B?

表1:

+-----------+ 
| Students | 
+-----------+ 
| S_PK  | 
| Mike  | 
| Joe  |  
| Bob  | 
| Bill  |  
+-----------+   

表2:

+--------+ 
| Grades | 
+--------+ 
| G_PK | 
| A |  
| A |  
| B |  
| C |  
| S_PK |  
+--------+ 

如何把一個查詢,讓我有當學生的比例是多少?

+1

你知道表和列之間的區別? –

+0

@GordonLinoff是的,我願意。他們的兩個獨立表格不是列。也許是因爲我正在使用管道符號來分離它們,並且它讓每個人都感到困惑,因爲它們看起來像列一樣。現在可以修復 – al56

回答

4

這是我從Gordon那裏學到的一個小技巧。

Select Pct= avg(case when Grades='A' then 1.0 else 0.0 end) 
From YourTable 

返回

0.500000 

編輯只是爲了好玩

Select [As] = avg(case when Grades='A' then 1.0 else 0.0 end) 
     ,[Bs] = avg(case when Grades='B' then 1.0 else 0.0 end) 
     ,[Cs] = avg(case when Grades='C' then 1.0 else 0.0 end) 
     ,[Ds] = avg(case when Grades='D' then 1.0 else 0.0 end) 
     ,[Fs] = avg(case when Grades='F' then 1.0 else 0.0 end) 
From YourTable 

返回

As   Bs   Cs   Ds   Fs 
0.500000 0.250000 0.250000 0.000000 0.000000 

編輯 - 更新問題

Select (A.n*1.0)/B.Den 
From (Select Num=count(Distinct S_PK) from Grades where Grade='A') A 
Cross Join (Select Den=count(Distinct S_PK) from Students) B 
+2

Overachiever !!!!並且也是對戈登的補充......你今天正在鋪設厚厚的男孩。 :P作爲說明它爲什麼1.0和0.0的原因是這樣SQL將強制系統避免整數數學給你十進制結果而不是0或1取決於四捨五入。 – xQbert

+0

@xQbert他知道這不是一個簡單的列過濾器嗎?這是完全兩個不同的表格。 – al56

+0

@ al56我認爲所提供的數據是兩張表格之間的連接結果。如果不是,你打算如何加入兩張表 –

相關問題