使用父表字段的SQL子查询过滤器

时间:2018-07-18 10:08:21

标签: sql sql-server

我有一个如下查询:

Location loc1 = new Location("");
loc1.setLatitude(lat1);
loc1.setLongitude(lon1);

Location loc2 = new Location("");
loc2.setLatitude(lat2);
loc2.setLongitude(lon2);

float distance = loc1.distanceTo(loc2);

int speed=30;
float time = distance/speed;

我在where子句中有一个子查询,可对每个项目应用过滤器,但此子查询联接与主查询中的联接相同,是否有任何方法可以重用主查询表并避免重复相同的代码在子查询中。

1 个答案:

答案 0 :(得分:1)

使用CTE。假设crm.acc.TransactionRequestCRM.acc.TransactionRequestHistory中的列名是不同的,则应该可以使用以下内容。如果不是,则必须在cte的Select中指定带有别名的列。

with cte as
(select * from crm.acc.TransactionRequest tr
                                    INNER JOIN CRM.acc.TransactionRequestHistory as trh
                                    ON tr.TransactionRequestID = trh.TransactionRequestFK)

SELECT AccountFK ,
          TransactionRequestStatus = CASE
            WHEN TransactionRequestStatusFK  = 2 THEN 'Accepted' 
            ELSE 'Rejected'
        END,
        TransactionRequestID

         FROM cte
         where TransactionRequestTypeFK = 3 --bill split
         and TransactionRequestStatusFK in (2, 3) --Approved, Rejected  

         --Filter- on each item
         and (TransactionRequestStatusFK = 2 and TransactionRequestID not in 
         (select TransactionRequestID from cte
                                      where TransactionRequestID = TransactionRequestFK
                                      and EventFK = 15)
                or
                TransactionRequestStatusFK = 3 and  Notes not like '%No Action%')  
        group by AccountFK, TransactionRequestStatusFK, TransactionRequestID