jeudi 16 juin 2016

SQL matrix single query

Here is my table design. Sorry unable to create the same in SQLFiddle.com as its not working for SQL Server.

Tables - click this to view db design

I have to show the information like for each reason how many bookings got canceled as well as I need to map them with the staff name in the user interface.

Expecting Output in UI

I have the below query to retrieve the no of canceled bookings for each staff.

SELECT DISTINCT bb.StaffUserId, uu.Name
    ,(
        SELECT COUNT(bc1.Id)
        FROM Cancellation bc1
        INNER  JOIN Bookings bb1 ON (bb1.Id = bc1.BookingId)
        WHERE bc1.Date >= '6/1/2016'
            AND bc1.Date <= '6/30/2016'         
            AND bb1.StaffUserId = bb.StaffUserId
        ) as CancelledBookings
FROM Cancellation bc
INNER JOIN Bookings bb ON (bb.Id = bc.BookingId)
INNER JOIN Users uu ON (uu.Id = bb.StaffUserId)
WHERE bc.Date >= '6/1/2016'
AND bc.Date <= '6/30/2016'

But the problem to show the reasons, I dynamically create the below query from code for each user and run them in the database.

SELECT COUNT(bc.Id)
FROM Cancellation bc
LEFT JOIN Bookings bb ON (bb.Id = bc.BookingId)
WHERE bc.Date >= '6/1/2016'
    AND bc.Date <= '6/30/2016'
    AND bb.StaffUserId = @@StaffId  
    AND bc.'ReplaceReasonStringInCode'= 1;

So I ends up with running the same query user X Reasons times 3*4=12 times. It slows as well when I run the report for 1 year with 50 users(50*4=200 queries).

Is there a way to avoid this dynamic query formation and running many times? Is it possible to achieve a the result with single query?

Aucun commentaire:

Enregistrer un commentaire