我有一个如下查询:
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子句中有一个子查询,可对每个项目应用过滤器,但此子查询联接与主查询中的联接相同,是否有任何方法可以重用主查询表并避免重复相同的代码在子查询中。
答案 0 :(得分:1)
使用CTE
。假设crm.acc.TransactionRequest
和CRM.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