简体   繁体   English

使用子选择外部的表进行SQL子选择查询

[英]SQL subselect queries with use of the table outside subselect

I'm trying to retrieve the count the number of times that a teammate has beat his teammate based on DRIVERPOSITION , however i keep getting that invalid select-list in subselect i guess this is because i use the b and a table inside the subselect query? 我正在尝试根据DRIVERPOSITION检索队友击败队友的DRIVERPOSITION ,但是我一直invalid select-list in subselect获取invalid select-list in subselect我想这是因为我在subselect查询中使用了ba表?

Sample Data 样本数据

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

DESIRED RESULT 期望的结果

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

What i tried so far 到目前为止我尝试过的

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');

I think this does what you want: 我认为这可以满足您的需求:

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;

However, I have no idea how this fits into your query. 但是,我不知道这如何适合您的查询。 Your sample data refers to one table. 您的示例数据引用一个表。 Your query has multiple table references. 您的查询具有多个表引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM