2017-04-17 209 views
0

我想要檢索一個隊友根據DRIVERPOSITION打敗他的隊友的次數,但是我總是收到invalid select-list in subselect我想這是因爲我使用ba表中的子查詢?使用外部表子查詢的SQL子查詢查詢

樣本數據

RACEID CONSTRUCTORID DRIVERID DRIVERPOSITION 
970  4    826  3    
970  4    807  7 
960  4    826  4    
960  4    807  7 
970  3    820  10    
970  3    810  12 
960  3    820  13    
960  3    810  11 

期望的結果

RACEID CONSTRUCTORID DRIVERID WINS 
970  4    826  2    
970  4    807  0 
960  3    820  1    
960  3    810  1 

我試過到目前爲止

SELECT 
(
SELECT COUNT(
CASE 
WHEN b.DRIVERPOSITION > a.DRIVERPOSITION THEN 1 
ELSE 0 END 
) 
FROM QUALIFYING b 
WHERE RACEYEAR = to_char(NOW(), 'YYYY') 
AND a.CONSTRUCTORID = b.CONSTRUCTORID 
AND a.RACEID = b.RACEID 
AND a.DRIVERID != b.DRIVERID 
) 
FROM QUALIFYING a 
INNER JOIN RACES 
ON a.RACEID = RACES.RACEID 
INNER JOIN DRIVERS 
ON a.DRIVERID = DRIVERS.DRIVERID 
INNER JOIN CONSTRUCTORS 
ON a.CONSTRUCTORID = CONSTRUCTORS.CONSTRUCTORID 
WHERE RACEYEAR = to_char(NOW(), 'YYYY'); 
+4

編輯你的問題並提供(1)樣本數據; (2)期望的結果; (3)您正在使用的數據庫的標籤。你有足夠高的聲譽,你應該知道如何提出一個好問題。 –

+0

更新了我的問題。 –

回答

1

我覺得這做你想要的:

select raceid, constructorid, driverid, 
     sum(case when seqnum = 1 then 1 else 0 end) as numwins 
from (select d.*, 
      row_number() over (partition by raceid, constructorid order by driverposition) as seqnum 
     from data d 
    ) d 
group by raceid, constructorid; 

但是,我不知道如何適合您的查詢。您的示例數據涉及一個表格。你的查詢有多個表引用。