Here is my query to retreive the report for each month to get the paid and unpaid bookings
SELECT tbc.tbcId
,tbc.tbcName
,(
SELECT COUNT(bb.bbId)
FROM MyBooking bb
WHERE bb.tbcId = tbc.tbcId
AND bb.bbIsPayed = 1
AND Year(bb.bbDate) = '2016' --proc parameter @year
AND Month(bb.bbDate) = '7' --proc parameter @month
) AS PaidCount
,(
SELECT SUM(CASE
WHEN bb.bbVAT = 1
THEN (bb.bbPrice / 100) * 80
ELSE bb.bbPrice
END)
FROM MyBooking bb
WHERE bb.tbcId = tbc.tbcId
AND bb.bbIsPayed = 1
AND Year(bb.bbDate) = '2016' --proc parameter @year
AND Month(bb.bbDate) = '7' --proc parameter @month
) AS PaidAmount
,(
SELECT COUNT(bb.bbId)
FROM MyBooking bb
WHERE bb.tbcId = tbc.tbcId
AND bb.bbIsPayed <> 1
AND Year(bb.bbDate) = '2016' --proc parameter @year
AND Month(bb.bbDate) = '7' --proc parameter @month
) AS UnpaidCount
,(
SELECT SUM(CASE
WHEN bb.bbVAT = 1
THEN (bb.bbPrice / 100) * 80
ELSE bb.bbPrice
END)
FROM MyBooking bb
WHERE bb.tbcId = tbc.tbcId
AND bb.bbIsPayed <> 1
AND Year(bb.bbDate) = '2016' --proc parameter @year
AND Month(bb.bbDate) = '7' --proc parameter @month
) AS UnPaidAmount
FROM BookingCategories tbc
WHERE tbc.tbcIncludeReport = 1
AND tbc.tbcId IN (
SELECT DISTINCT con.tbcId
FROM CategoryXTags con
WHERE (
con.ttId = 26
OR con.ttId = 23
OR con.ttId = 24
)
)
ORDER BY tbc.tbcName ASC;
I have to run this for a given period of time, example Jan 2016 to Aug 2016.
As of now I run this in a loop by passing a @year and @month variable.
Is it possible to just pass @FromDate and @Todate and generate the report for each month in a same query? I couldnt able to think much in SQL to achieve this.
Untested, but I think will shrink your process down
Declare @Date1 Date = '2016-01-01'
Declare @Date2 Date = '2016-08-31'
Select Period = EOMonth(bb.bbDate)
,tbc.tbcId
,tbc.tbcName
,PaidCount = sum(case when bb.bbIsPayed=1 then 1 else 0 end)
,PaidAmount = sum(case when bb.bbIsPayed=1 and 1bb.bbVAT = 1 Then (bb.bbPrice / 100) * 80 ELSE bb.bbPrice end)
,UnpaidCount = sum(case when bb.bbIsPayed<>1 then 1 else 0 end)
,UnPaidAmount = sum(case when bb.bbIsPayed <> 1 and bb.bbVAT = 1 Then (bb.bbPrice / 100) * 80 ELSE bb.bbPrice end)
From BookingCategories tbc
Join MyBooking bb on (bb.bbId = tbc.tbcId)
Where tbc.tbcIncludeReport = 1
and tbc.tbcId IN (26,26,24)
and bb.bbDate between @Date1 and @Date2
Group By
EOMonth(bb.bbDate)
,tbc.tbcId
,tbc.tbcName
Order By 1,tbc.tbcName ASC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.