This is an example where I would like to use SQL Views. I have two tables: Timesheet and Invoice.
Timesheet
ConsultantKey
CustometKey
Date
StartTime
EndTime
Invoice
ConsultantKey
CustometKey
InvoiceNo
InvoiceDate
StartDate
EndDate
Rate
Taxe1
Taxe2
An invoice is created by selecting all TimeSheet that the date are between Invoice.StartDate and Invoice.EndDate, for a given ConsultantKey and CustometKey.
First I created a view for the timesheet that calculates the time difference for display and for more calculations.
CREATE VIEW AS TimesheetView
SELECT
ConsultantKey
CustometKey
Date
SEC_TO_TIME(TIME_TO_SEC(EndTime) - TIME_TO_SEC(StartTime)) AS DiffHHMM,
ROUND((TIME_TO_SEC(EndTime) - TIME_TO_SEC(StartTime)) / 3600,2) AS DiffDecimalHour,
FROM Timesheet
Then I use this VIEW to create a second VIEW for applying to an Invoice report detail.
CREATE VIEW AS InvoiceTimesheetView
SELECT
I.ConsultantKey,
I.CustometKey,
I.InvoiceNo,
I.InvoiceDate,
I.StartDate,
I.EndDate,
TV.Date,
TV.DiffHHMM,
TV.DiffDecimalHour
FROM
Invoice I
JOIN
TimesheetView TV ON TV.Date >= I.StartDate AND TV.Date <= I.EndDate
AND TV.ConsultantKey = I.ConsultantKey
AND TV.CustometKey = I.CustometKey
and the Invoice report summary
CREATE VIEW AS InvoiceSumView
SELECT
I.ConsultantKey,
I.CustometKey,
I.InvoiceNo,
I.InvoiceDate,
I.StartDate,
I.EndDate,
I.Rate,
I.Taxe1,
I.Taxe2,
SUM(FT.DiffDecimalHour) AS TotalHours,
ROUND(SUM(DiffDecimalHour) * I.Rate,2) AS TotalAmount,
ROUND(SUM(DiffDecimalHour) * I.Rate * (I.Taxe1/100),2) AS Taxe1Amount,
ROUND(SUM(DiffDecimalHour) * I.Rate * (I.Taxe2/100),2) As Taxe2Amount ,
FROM
Invoice I
JOIN
TimesheetView TV ON TV.Date >= I.StartDate AND TV.Date <= I.EndDate
AND TV.ConsultantKey = I.ConsultantKey
AND TV.CustometKey = I.CustometKey
Finally I re-use these Views filtered like this: SELECT * FROM InvoiceTimesheetView WHERE I.ConsultantKey = ? AND I.CustometKey ?
The last view will be re-used for many other forms or reports, such a statistics, amount of total taxe received in a year, list of customers who have not pay yet, total amount earn in a year per customer, etc…
So for each of these requests, i don’t want to re-create huge SQL queries difficult to read and error prones.
I wonder how I can handle easily these complex queries without using SQL VIEWS.
Regards,
Jean