Hi all,
We are using Microsoft SQL Server 2008 and are querying a SQL view that contains information about our egg grade percentages for each farm.
A manager wants as part of the query if a farm does not exist for the last seven days then it is it return a default percentage of one for the farm per egg type.
If there is data, then the data will be returned as per the information in the view.
The below code is working, however I need to combine for each farm (we have 15 farms in total). I have tried UNION ALL but the SQL is not liking the statement.
My SQL knowledge is fairly good, but this is a bit beyond me. Please can someone help.
We are using Microsoft SQL Server 2008 and are querying a SQL view that contains information about our egg grade percentages for each farm.
A manager wants as part of the query if a farm does not exist for the last seven days then it is it return a default percentage of one for the farm per egg type.
If there is data, then the data will be returned as per the information in the view.
The below code is working, however I need to combine for each farm (we have 15 farms in total). I have tried UNION ALL but the SQL is not liking the statement.
My SQL knowledge is fairly good, but this is a bit beyond me. Please can someone help.
SQL:
DECLARE @FromDate date
DECLARE @ToDate date
SET @FromDate = CONVERT(date, DATEADD(d,-7,getdate()))
SET @ToDate = CONVERT(date, getdate())
IF NOT EXISTS(
SELECT LEFT(t0.SupplierName,LEN(t0.SupplierName)-2) As Farm, t0.Dscription, (case when t0.Dscription = 'Oversize' then sum(t0.Eggs) / sum(t0.TotalEggs/2) else sum(t0.Eggs) / sum(t0.TotalEggs) end)*100 As EggPercent
FROM dbo.Paul_MOBA_History_SB t0
WHERE t0.FirstDate >= @FromDate and t0.FirstDate <= @ToDate AND LEFT(t0.SupplierName,LEN(t0.SupplierName)-2) = 'Berkana Park'
GROUP BY t0.SupplierName, t0.Dscription)
BEGIN
SELECT 'Berkana Park' As Farm, t0.Dscription, 1 As EggPercent
FROM dbo.Paul_MOBA_History_SB t0
WHERE t0.FirstDate >= @FromDate and t0.FirstDate <= @ToDate AND t0.SupplierName not like '%Strathbogie%' AND t0.SupplierName not like '%Dirties rewash%' AND t0.SupplierName not like '%End of Day%' AND t0.SupplierName not like '%NOSAP%'
GROUP BY t0.Dscription
END
ELSE
BEGIN
SELECT LEFT(t0.SupplierName,LEN(t0.SupplierName)-2) As Farm, t0.Dscription, (case when t0.Dscription = 'Oversize' then sum(t0.Eggs) / sum(t0.TotalEggs/2) else sum(t0.Eggs) / sum(t0.TotalEggs) end)*100 As EggPercent
FROM dbo.Paul_MOBA_History_SB t0
WHERE t0.FirstDate >= @FromDate and t0.FirstDate <= @ToDate AND t0.SupplierName like '%Berkana%'
GROUP BY t0.SupplierName, t0.Dscription
END