Search code examples
sqlsubquerycorrelated-subquery

get the count from query


Select Count(*),
(select Name from Tours Where Tours.ID = TourBooking.TourID) as Name,
(select Url from Tours Where Tours.ID = TourBooking.TourID) as Url,
(select Top 1 Name from TourImages Where TourImages.TourID = TourBooking.TourID Order By ID Asc) as ImageName,
(Select Duration +' '+ CASE WHEN  DurationType = 'd' THEN 'Day(s)' WHEN  DurationType = 'h' THEN 'Hour(s)' END from Tours Where Tours.ID = TourBooking.TourID)as Duration,
(select replace(replace('<a> Adult(s) - <c> Children','<a>', sum(case when [Type] = 1 then 1 else 0 end)                      ),
'<c>', sum(case when [Type] = 2 then 1 else 0 end)) from TourPerson Where TourPerson.BookingId = TourBooking.ID) as TotalPassengers,
StartDate,CreatedDate as BookingDate,ID as BookingID,[Status],ServicePrice
from TourBooking

How to get the count from this query


Solution

  • How to get the count from this query

    I think you're trying to do that with your first COUNT(*) statement. Instead you could try nesting your whole query and get the count that way.

    SELECT COUNT(innerTable.*), innerTable.* FROM (
    SELECT
    (select Name from Tours Where Tours.ID = TourBooking.TourID) as Name,
    (select Url from Tours Where Tours.ID = TourBooking.TourID) as Url,
    (select Top 1 Name from TourImages Where TourImages.TourID = TourBooking.TourID Order By ID Asc) as ImageName,
    (Select Duration +' '+ CASE WHEN  DurationType = 'd' THEN 'Day(s)' WHEN  DurationType = 'h' THEN 'Hour(s)' END from Tours Where Tours.ID = TourBooking.TourID)as Duration,
    (select replace(replace('<a> Adult(s) - <c> Children','<a>', sum(case when [Type] = 1 then 1 else 0 end)                      ),
    '<c>', sum(case when [Type] = 2 then 1 else 0 end)) from TourPerson Where TourPerson.BookingId = TourBooking.ID) as TotalPassengers,
    StartDate,CreatedDate as BookingDate,ID as BookingID,[Status],ServicePrice
    from TourBooking ) as innerTable