2017-02-26 110 views
0

假設你有兩張桌子。如何計算SQL中的百分比差異?

Table 1 - T 
Columns 
City ID(Foreign keyed to C.cityid) 
Completed (yes or no) 
NumberOne (integer) 
NumberTwo (integer) 
Date (timestamp with timezone) 

Table 2 - C 
City ID (integer) 
City Name (string) 

對於每個城市的「A」和「B」的,我怎麼計算的Numberone和NumberTwo之間的所有事情完成內最近30天的第90個百分點的差別。

這是我到目前爲止有:

SELECT 
    100.0*(T.NumberOne - T.NumberTwo)/T.NumberTwo As PercentDiff 
FROM T 
JOIN C ON CityID 

我是新來的SQL和不知道如何爲這一切創造一個查詢。我是否需要使用子查詢?

+3

請與您正在使用的數據庫標記您的問題。 –

回答

1

嘗試這樣:

SELECT 
    100.0*(t.NumberOne - t.NumberTwo)/t.NumberTwo As PercentDiff 
from T t 
inner join C c 
on t.[City ID] = c.[City ID] 
where c.Name in ('A','B') 
and t.Completed = 'yes' 
and t.Date > DATEADD(day, -30, GETDATE()) 
+0

如果是第90百分位,那麼我應該將100.0改爲90.0吧?只是想第二個意見......感謝您的回答! – pr338

0

嘗試ON CITYID = CITYID in語句需要一個布爾表達式。