Am interested to know how correct is my query the question is posted here., I doubt If I have written a perfect one, and I wish to ask you all where can I improve my code.
Note: I did not want to fill this place up with lot of code, was very brief. Thank you.
SELECT a.BookingId AS BookingId,
CAST(b.TransactionDateTime AS DATE) AS TransactionDate
FROM TC33_AuditTrial A
JOIN TC33_AuditTrial b
ON a.AuditId = b.AuditId
WHERE a.TransactionType = 'S'
AND CAST(a.TransactionDateTime AS DATE) =
(SELECT CAST(b.TransactionDateTime AS DATE)
FROM TC33_AuditTrial b
WHERE b.BookingId = a.BookingId
AND b.AuditId =
(SELECT MAX(b.AuditId)
FROM TC33_AuditTrial b
WHERE a.BookingId = b.BookingId
AND b.TransactionType = 'R'
)
)
AND a.TransactionValue =
(SELECT SUM(b.TransactionValue)
FROM TC33_AuditTrial b
WHERE a.BookingId = b.BookingId
AND b.TransactionType = 'R'
)
Undeleted
My original answer was
Which I was quite pleased with as it just took one pass through the data.
Then I noticed the updated bit of the spec that it has to be restricted to the first date that contains an entry for that booking. The only way I could think to do this was to add a sub query that increased the cost of the query quite dramatically.
The frustrating aspect though is that I want to restrict the results to the first day for each BookingId and I am already grouping by BookingId, Day
It feels like there might be some clever way of getting this restriction without the sub query but if so it has eluded me so far!
I just managed to get the ‘OVER’ working. I wouldn’t have posted this answer until after the competition was closed except it has exactly the same query plan as the one posted by 8kb