0
我對SQL服務器相當陌生,正在學習,因爲如果答案很明顯,或者我只是以完全錯誤的方式來處理這個問題,我很抱歉。子查詢中的T-sql子查詢
我正在將查詢從訪問移到SQL服務器,有問題的查詢在子查詢中有子查詢。
WITH CalculateSPBalance AS
(SELECT [BOOKINGS FILE].[Booking Number], ([Promoter Codes].[Promoter's Price] + [Promoter Codes].[Resform Deposit] * [Promoter Codes].[Resform Deposit deducted from sp] -
[Venue Codes].[Event Price]) - [Venue Codes].[Event Deposit] * [BOOKINGS FILE].[Charity paid event deposit] AS [SP Balance]
FROM [BOOKINGS FILE]
INNER JOIN [Promoter Codes] ON [BOOKINGS FILE].[Promoter Code] = [Promoter Codes].[Promoter Code]
INNER JOIN [Venue Codes] ON [BOOKINGS FILE].[Venue Code] = [Venue Codes].[Venue Code]
)
, CalculateSPBeingHeld AS
(SELECT [BOOKINGS FILE].[Booking Number], SUM([Sponsorship Collected].Amount) AS [SP held]
FROM [BOOKINGS FILE]
LEFT OUTER JOIN [Sponsorship Collected] ON [BOOKINGS FILE].[Booking Number] = [Sponsorship Collected].[Booking Number]
WHERE ([Sponsorship Collected].[Received by] = N'holding')
GROUP BY [BOOKINGS FILE].[Booking Number]
)
SELECT [BOOKINGS FILE].[Booking Number],
CASE
WHEN CalculateSPBeingHeld.[SP held] IS NULL
THEN 0
ELSE CalculateSPBeingHeld.[sp held] - CalculateSPBalance.[SP Balance]
END AS test
FROM [Bookings file]
INNER JOIN CalculateSPBalance ON[BOOKINGS FILE].[Booking Number] = CalculateSPBalance.[Booking Number]
INNER JOIN CalculateSPBeingHeld ON[BOOKINGS FILE].[Booking Number] = CalculateSPBeingHeld.[Booking Number]
ORDER BY [booking number]
據我所知,這兩個潛艇是在整個查詢中定義和使用的。
這工作正常。
我將如何再使用這些結果作爲一個大的查詢
即
WITH test2 AS
(
CalculateSPBalance AS
(SELECT [BOOKINGS FILE].[Booking Number], ([Promoter Codes].[Promoter's Price] + [Promoter Codes].[Resform Deposit] * [Promoter Codes].[Resform Deposit deducted from sp] -
[Venue Codes].[Event Price]) - [Venue Codes].[Event Deposit] * [BOOKINGS FILE].[Charity paid event deposit] AS [SP Balance]
FROM [BOOKINGS FILE]
INNER JOIN [Promoter Codes] ON [BOOKINGS FILE].[Promoter Code] = [Promoter Codes].[Promoter Code]
INNER JOIN [Venue Codes] ON [BOOKINGS FILE].[Venue Code] = [Venue Codes].[Venue Code])
, CalculateSPBeingHeld AS
(SELECT [BOOKINGS FILE].[Booking Number] , SUM([Sponsorship Collected].Amount) AS [SP held]
FROM [BOOKINGS FILE]
LEFT OUTER JOIN [Sponsorship Collected] ON [BOOKINGS FILE].[Booking Number] = [Sponsorship Collected].[Booking Number]
WHERE ([Sponsorship Collected].[Received by] = N'holding')
GROUP BY [BOOKINGS FILE].[Booking Number]
)
SELECT [BOOKINGS FILE].[Booking Number],
CASE
WHEN CalculateSPBeingHeld.[SP held] IS NULL
THEN 0
ELSE CalculateSPBeingHeld.[sp held] - CalculateSPBalance.[SP Balance]
END AS test
FROM [Bookings file]
INNER JOIN CalculateSPBalance ON[BOOKINGS FILE].[Booking Number] = CalculateSPBalance.[Booking Number]
INNER JOIN CalculateSPBeingHeld ON[BOOKINGS FILE].[Booking Number] = CalculateSPBeingHeld.[Booking Number]
ORDER BY [booking number]
)
SELECT *
FROM test2
所以我想一個大的查詢中使用此數據集由子查詢的子查詢的一部分
感謝先進
什麼問題?並在格式上工作。 – Paparazzi