Related
SELECT DISTINCT
ATB.AcountCountDesc,
TB.LastFirstName,
N.EMAIL,
TB.AccountNumber,
TB.OpenShareCount,
TB.MemberOpenDate,
TB.OpenMemberCount,
TB.OpenShareBalance,
SH.ShareType,
FORMAT(SH.ShareOpenDate, 'MM/dd/yyyy') AS "ShareOpenDate",
SH.ShareCreatedByUser,
SH.ShareCreatedByUserName,
SH.ShareBranchName,
SH.ShareBranch,
cast(month(SH.ShareOpenDate) as varchar) + '/' + cast(year(SH.ShareOpenDate) as varchar) as 'Open Period',
CONCAT(SH.ShareCreatedByUser, '-',SH.ShareCreatedByUserName) 'Opened By'
FROM
arcu.vwARCUOperationMemberTrialBalance as TB
INNER JOIN arcu.vwARCUOperationMemberAccountTrialBalance as ATB ON TB.MemberSuppID = ATB.MemberID
and TB.ProcessDate = ATB.PDate
and TB.MemberStatus = 0 -- Account count for open Members only
and TB.AccountStatus <> 1
INNER JOIN arcu.vwARCUShare AS SH ON TB.ProcessDate = SH.ProcessDate
AND TB.AccountNumber = SH.AccountNumber
INNER JOIN NAME AS N ON TB.AccountNumber = N.PARENTACCOUNT
WHERE
ATB.AcountCountDesc = 1
AND TB.OpenShareCount >= 1
AND SH.ShareType = '00'
AND SH.ShareID != '40'
AND SH.ShareOpenDate >= DATEADD(s, 1, DATEADD(mm, DATEDIFF(m, 0, GETDATE()), -2))
AND TB.MemberOpenDate = SH.ShareOpenDate
AND N.EMAIL <> ''
AND N.EMAIL is not null
order by MemberOpenDate Desc;
Issue: the MemberOpen Date starts on 08/02/2021.
Desired outcome: I need it to start on 08/01/2021
What I have tried: I have tried declaring a variable and calculating the start of the month by using datediff and still get the 08/02/2021 outcome.
I tried changing the => to = or <= and the issue persists. Please help.
You could calculate the 1st of the month using EOMONTH something like this
SELECT DISTINCT ATB.AcountCountDesc,TB.LastFirstName,N.EMAIL,TB.AccountNumber,TB.OpenShareCount,TB.MemberOpenDate,
TB.OpenMemberCount,TB.OpenShareBalance,SH.ShareType,FORMAT(SH.ShareOpenDate,'MM/dd/yyyy') AS "ShareOpenDate",
SH.ShareCreatedByUser,SH.ShareCreatedByUserName,SH.ShareBranchName,SH.ShareBranch,cast(month(SH.ShareOpenDate)
as varchar) + '/' + cast(year(SH.ShareOpenDate) as varchar)as 'Open Period', CONCAT(SH.ShareCreatedByUser,'-',SH.ShareCreatedByUserName)
'Opened By'
FROM arcu.vwARCUOperationMemberTrialBalance as TB
JOIN arcu.vwARCUOperationMemberAccountTrialBalance as ATB
ON TB.MemberSuppID = ATB.MemberID
and TB.ProcessDate = ATB.PDate
and TB.MemberStatus = 0 -- Account count for open Members only
and TB.AccountStatus <> 1
JOIN arcu.vwARCUShare AS SH
ON TB.ProcessDate = SH.ProcessDate
AND TB.AccountNumber = SH.AccountNumber
JOIN NAME AS N ON TB.AccountNumber = N.PARENTACCOUNT
WHERE
ATB.AcountCountDesc = 1 AND
TB.OpenShareCount >= 1 AND
SH.ShareType = '00' AND
SH.ShareID !='40' AND
SH.ShareOpenDate >= (select dateadd(day, 1, dateadd(month, -1, eomonth(getdate())))) AND
TB.MemberOpenDate = SH.ShareOpenDate AND
N.EMAIL <> '' AND
N.EMAIL is not null
order by MemberOpenDate Desc;
I am trying to put a statement together the first part of the code works.
DECLARE #FYEND date, #YTD date, #PYTD date, #Openmonth date, #Monthtodatefrom date, #Monthtodateto date, #Priormonthdatefrom date, #Priormonthdateto date, #Currentmonth date
SET #FYEND = Dateadd(year,1,DATEADD(year,DATEDIFF(month,'19010701', getdate() ) /12,'19010701'))
SET #YTD = GETDATE()
SET #PYTD = DATEADD(YEAR,-1,#YTD)
SET #Openmonth = dateadd(DAY,1,dateadd(YEAR,-1,EOMONTH(#YTD,-1)))
SET #Monthtodatefrom = EOMONTH(getdate(),-2)
SET #Monthtodateto = Dateadd(DAY,1,eomonth(#ytd,-1))
SET #Priormonthdatefrom= DATEADD(YEAR,-1,#monthtodatefrom)
SET #Priormonthdateto= dateadd(year,-1,Dateadd(DAY,1,eomonth(#ytd,-1)))
SET #Currentmonth=dateadd(DAY,1,EOMONTH(getdate(),-1))
SELECT
b.T3,
b.Country_name,
b.Division_Name,
b.SHOP_NAME,
b.Shop_Type,
b.MTD_Result
FROM
(
SELECT
a.T3,
a.Country_name,
a.Division_Name,
a.SHOP_NAME,
a.Shop_Type,
sum(case when coa.EBIT in ('EBIT') then gl.Amount ELSE 0 END) as MTD_Result
FROM
(
SELECT
s.T3,
s.DIVISION_NAME as Division_Name,
s.SHOP_NAME,
s.COUNTRY_NAME as Country_name,
s.[Business Grouping] as Shop_Type
FROM Finance_PRD.dbo.Shops s
WHERE
s.DIVISION_NAME in ('NSWACT FCB Retail North', 'NSWACT FCB Retail South', 'Vicmania', 'The Heartland', 'SA FCB Retail', 'WANT FCB Retail', 'UT Leisure', 'TA Leisure', 'Contact Centre')
and s.BUSTYPE='ARET'
and s.[Open Date] < #Currentmonth
and s.[Close Date] is null
and s.T3 = '497088'
GROUP BY
s.T3,
s.SHOP_TYPE,
s.PRIMARY_STORE_T3,
s.DIVISION_NAME,
s.t3,
s.SHOP_NAME,
s.COUNTRY_NAME,
s.[Business Grouping],
s.BUSINESS_GROUPING_NAME,
s.SHOP_NAME) a
INNER JOIN Finance_PRD.ANZ.ConsolidatedAUD as gl
on a.T3 = gl.T3
INNER JOIN Finance_PRD.dbo.ChartOfAccounts coa
on gl.AccountCode = coa.Code
WHERE gl.Period > CASE WHEN MONTH(#Monthtodatefrom) <= 6 THEN
CONCAT(YEAR(#Monthtodatefrom), RIGHT(CONCAT('000', MONTH(#Monthtodatefrom) + 6), 3))
ELSE CONCAT(YEAR(#Monthtodatefrom) + 1, RIGHT(CONCAT('000', MONTH(#Monthtodatefrom) - 6), 3))
END and gl.Period < CASE WHEN MONTH(#Monthtodateto) <= 6 THEN
CONCAT(YEAR(#Monthtodateto), RIGHT(CONCAT('000', MONTH(#Monthtodateto) + 6), 3))
ELSE CONCAT(YEAR(#Monthtodateto) + 1, RIGHT(CONCAT('000', MONTH(#Monthtodateto) - 6), 3))
END
GROUP BY
a.T3,
a.Country_name,
a.Division_Name,
a.SHOP_NAME,
a.Shop_Type
)b
but when I want to join on a second statement it does not return a value, I require the second statement to be 0 if there is no join.
Second part of the code is here which I set below query b
Inner join Finance_PRD.ANZ.ConsolidatedAUD as gl
on b.T3 = gl.T3
Inner JOIN Finance_PRD.dbo.ChartOfAccounts coa
on gl.AccountCode = coa.Code
WHERE gl.Period > CASE WHEN MONTH(#Priormonthdatefrom) <= 6 THEN
CONCAT(YEAR(#Priormonthdatefrom), RIGHT(CONCAT('000', MONTH(#Priormonthdatefrom) + 6), 3))
ELSE CONCAT(YEAR(#Priormonthdatefrom) + 1, RIGHT(CONCAT('000', MONTH(#Priormonthdatefrom) - 6), 3))
END and gl.Period < CASE WHEN MONTH(#Priormonthdateto) <= 6 THEN
CONCAT(YEAR(#Priormonthdateto), RIGHT(CONCAT('000', MONTH(#Priormonthdateto) + 6), 3))
ELSE CONCAT(YEAR(#Priormonthdateto) + 1, RIGHT(CONCAT('000', MONTH(#Priormonthdateto) - 6), 3))
END
I've tried to understand all the different joins and even attempted to use is null, if and coalesce to no avail.
...................
LEFT JOIN
(
Finance_PRD.ANZ.ConsolidatedAUD as gl
INNER JOIN Finance_PRD.dbo.ChartOfAccounts coa on gl.AccountCode = coa.Code
) on a.T3 = gl.T3
WHERE gl.Period IS NULL OR (gl.Period > CASE WHEN MONTH(#Monthtodatefrom) <= 6 THEN ....)
Im having a problem with this :( is this because of my select statement? or any join? derived table? or my CASE syntax?
The error occurs the time I put this CASE syntax: CASE WHEN dbo.AdditionalInfo.UserDefined3 = 1 THEN 2
because before it is just:
CASE WHEN WorkOrder.DateCreated < (CASE WHEN (DATEPART(dw,
dbo.ToBeScheduled_InProgress.Start) = 2) THEN (ToBeScheduled_InProgress.Start + 0.625) - 3 ELSE (ToBeScheduled_InProgress.Start + 0.625) - 1 END) THEN 1 ELSE 2 END AS ScheduleTime
SELECT Start, UserDefined3, ItemNo, Name, TotalQtyRequired, PreviouslyCounted, QtyLeftToPick, LocationCode, Location, Rack, QtyInRack, PickQty, CellCode, UDMaterial, UDMaterialSort, ScheduleTimeFROM (SELECT dbo.ToBeScheduled_InProgress.Start, dbo.ItemSpecs.ItemNo, dbo.ItemSpecs.Name, SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0))
AS TotalQtyRequired, ISNULL(RackedInventory.PreviouslyCounted, 0) AS PreviouslyCounted, SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0))
- ISNULL(RackedInventory.PreviouslyCounted, 0) AS QtyLeftToPick, RackedInventory.LocationCode, RackedInventory.Location, RackedInventory.Rack, ISNULL(RackedInventory.QtyInRack, 0) AS QtyInRack,
ISNULL(CASE WHEN SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0)) - ISNULL(RackedInventory.PreviouslyCounted, 0)
< RackedInventory.QtyInRack THEN SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0)) - ISNULL(RackedInventory.PreviouslyCounted, 0)
ELSE RackedInventory.QtyInRack END, 0) AS PickQty, dbo.ToBeScheduled_InProgress.CellCode, dbo.ItemSpecs.Userdefined2 AS UDMaterial, CASE WHEN dbo.ItemSpecs.Userdefined2 IN ('Foam', 'Wood',
'Plastic Inner', 'Rubber') THEN 0 ELSE 1 END AS UDMaterialSort, CASE WHEN dbo.AdditionalInfo.UserDefined3 = 1 THEN 2 WHEN WorkOrder.DateCreated < (CASE WHEN (DATEPART(dw,
dbo.ToBeScheduled_InProgress.Start) = 2) THEN (ToBeScheduled_InProgress.Start + 0.625) - 3 ELSE (ToBeScheduled_InProgress.Start + 0.625) - 1 END) THEN 1 ELSE 2 END AS ScheduleTime
FROM dbo.ToBeScheduled_InProgress INNER JOIN
dbo.OpenCalendarDaysTable AS OpenCalendarDays ON dbo.ToBeScheduled_InProgress.Start BETWEEN OpenCalendarDays.CalendarDateForwardRangeStart AND
OpenCalendarDays.CalendarDateForwardRangeEnd AND OpenCalendarDays.CalendarLinkID IS NULL INNER JOIN
dbo.OpenCalendarDaysTable AS PriorOpenCalendarDays ON OpenCalendarDays.CalendarOpenDayID = PriorOpenCalendarDays.CalendarOpenDayID + 1 AND OpenCalendarDays.CalendarLinkID IS NULL
INNER JOIN
dbo.ItemSpecFullStruc ON dbo.ToBeScheduled_InProgress.ItemSpecID = dbo.ItemSpecFullStruc.RootItemSpecID INNER JOIN
dbo.ItemSpecs ON dbo.ItemSpecFullStruc.ChildItemSpecID = dbo.ItemSpecs.ItemSpecID LEFT OUTER JOIN
dbo.WorkOrder ON dbo.ToBeScheduled_InProgress.WorkOrderID = dbo.WorkOrder.WorkOrderID LEFT OUTER JOIN
(SELECT InventoryByLocation.ItemID, InventoryByLocation.ItemNo, InventoryByLocation.ItemDescription, InventoryByLocation.LocationCode, InventoryByLocation.Location, InventoryByLocation.Rack,
InventoryByLocation.QtyInRack, SUM(PreviouslyCounted.QtyInRack) AS PreviouslyCounted
FROM (SELECT Rack, SUM(ISNULL(QtyToStock, ' ')) AS QtyInRack, ItemID, ItemSpecID, LocationID
FROM dbo.InventoryItems WITH (NOLOCK)
GROUP BY ItemID, ItemSpecID, LocationID, Rack) AS PreviouslyCounted RIGHT OUTER JOIN
(SELECT Items_1.ItemNo, Items_1.Name AS ItemDescription, Locations_1.LocationCode, Locations_1.DescriptionMed AS Location, InventoryItems_1.Rack,
SUM(dbo.Val(ISNULL(InventoryItems_1.QtyToStock, ''))) AS QtyInRack, UOMs_1.UOMCode AS StockUOM, InventoryItems_1.ItemID, InventoryItems_1.ItemSpecID,
Locations_1.LocationID
FROM dbo.Items AS Items_1 WITH (NOLOCK) INNER JOIN
dbo.Locations AS Locations_1 WITH (NOLOCK) INNER JOIN
dbo.InventoryItems AS InventoryItems_1 WITH (NOLOCK) LEFT OUTER JOIN
dbo.UOMs AS UOMs_1 WITH (NOLOCK) ON InventoryItems_1.StockUOMID = UOMs_1.UOMID ON Locations_1.LocationID = InventoryItems_1.LocationID ON
Items_1.ItemID = InventoryItems_1.ItemID
WHERE (Locations_1.LocationID = 7)
GROUP BY Locations_1.LocationCode, Items_1.ItemNo, Locations_1.DescriptionMed, Items_1.Name, UOMs_1.UOMCode, InventoryItems_1.ItemID, InventoryItems_1.ItemSpecID,
Locations_1.LocationID, InventoryItems_1.Rack
HAVING (SUM(dbo.Val(ISNULL(InventoryItems_1.QtyToStock, ''))) > 0)) AS InventoryByLocation ON PreviouslyCounted.Rack < InventoryByLocation.Rack AND
PreviouslyCounted.LocationID = InventoryByLocation.LocationID AND PreviouslyCounted.ItemID = InventoryByLocation.ItemID
GROUP BY InventoryByLocation.ItemNo, InventoryByLocation.ItemDescription, InventoryByLocation.LocationCode, InventoryByLocation.Location, InventoryByLocation.Rack, InventoryByLocation.QtyInRack,
InventoryByLocation.ItemID) AS RackedInventory ON dbo.ItemSpecs.ItemID = RackedInventory.ItemID
WHERE (dbo.ToBeScheduled_InProgress.ExcludeFromFiniteScheduling = 0) AND (ISNULL(dbo.ItemSpecs.Userdefined2, '') <> 'Covering') AND (dbo.ItemSpecs.InventoryTrackingID > 1)
GROUP BY dbo.ToBeScheduled_InProgress.Start, dbo.ItemSpecs.ItemNo, dbo.ItemSpecs.Name, RackedInventory.Rack, ISNULL(RackedInventory.PreviouslyCounted, 0), RackedInventory.Location,
RackedInventory.LocationCode, dbo.ToBeScheduled_InProgress.CellCode, dbo.ItemSpecs.Userdefined2,
CASE WHEN dbo.AdditionalInfo.UserDefined3 = 1 THEN 2 WHEN WorkOrder.DateCreated < (CASE WHEN (DATEPART(dw, dbo.ToBeScheduled_InProgress.Start) = 2) THEN (ToBeScheduled_InProgress.Start + 0.625)
- 3 ELSE (ToBeScheduled_InProgress.Start + 0.625) - 1 END) THEN 1 ELSE 2 END, RackedInventory.QtyInRack
HAVING (SUM(ISNULL(dbo.ToBeScheduled_InProgress.RemainingQty, 0) * ISNULL(dbo.ItemSpecFullStruc.TotalQtyPerRoot, 0)) - ISNULL(RackedInventory.PreviouslyCounted, 0) > 0)) AS _RackSort_Lean_AMPM ORDER BY Start, LocationCode, Rack
I know similar questions have been covered for this topic, I've looked through the answers but I just can't work out how to apply to this query unfortunately.
I know that adding 'pe.short_name' to GROUP BY isn't the best way to handle this either.
Any suggestions very much appreciated..
Column 'pe.short_name' invalid in select list because it is contained
in either an aggregate function or the GROUP BY clause.`
SELECT CASE
WHEN SUBSTRING(s.description, 13, 1) = '.'
THEN LEFT(s.description, 17)
ELSE LEFT(s.description, 12)
END WBSCode
,pe.short_name
,pn.description ProjectName
,(
SELECT description
FROM structure
WHERE structure_code = pe.code346
) ActivePortfolio
,CASE
WHEN ast.Description = 'WAIO'
THEN anc.Description
ELSE site.Description
END SiteFunction
,CASE
WHEN SUBSTRING(jv.description, 5, 1) = ' '
THEN LEFT(jv.description, 4)
WHEN SUBSTRING(jv.description, 7, 1) = ' '
THEN LEFT(jv.description, 6)
ELSE jv.Description
END AS JointVenture
,(
SELECT description
FROM structure
WHERE structure_code = pe.code79
) AssetClassification
,(
SELECT description
FROM structure
WHERE structure_code = pe.code390
) InvestmentSize
,(
SELECT RIGHT(import_code, 6)
FROM structure
WHERE structure_code = pe.code79
) AssetClassCode
,CAST(p.period_start AS DATE) Period_Start
,SUM(CASE
WHEN be.currency_code = 'AUD'
AND #Currency = 'AUD'
THEN be.amount
WHEN be.currency_code = 'USD'
AND #Currency = 'USD'
THEN be.amount
WHEN be.currency_code = 'AUD'
AND #Currency = 'USD'
THEN be.amount * ip.pfn_exch_rate_on_date(p.period_start, be.currency_code)
WHEN be.currency_code = 'USD'
AND #Currency = 'AUD'
THEN be.amount * (ip.pfn_exch_rate_on_date(p.period_start, be.currency_code) / ip.pfn_exch_rate_on_date(p.period_start, 'AUD'))
END) Amount
FROM fm_budget_entry be
JOIN fm_period p ON be.period_id = p.period_id
JOIN fm_budget_line bl ON be.line_id = bl.line_id
AND bl.version_id = #FinancialVersion
JOIN fm_budget_line_attrib la ON la.line_id = bl.line_id
AND la.line_attrib_code = 'Wbs138'
JOIN structure s ON la.line_attrib_value = s.structure_code
JOIN fm_account fa ON bl.account_code = fa.account_code
JOIN planning_entity pe ON pe.planning_code = bl.structure_code
JOIN structure ast ON ast.structure_code = pe.code713
AND ast.Description IN (#Assets)
JOIN structure pn ON pn.structure_code = pe.planning_code
LEFT JOIN structure site ON site.structure_code = pe.code37
LEFT JOIN structure_tree tr ON tr.dsc_code = pe.planning_code
AND tr.anc_Depth = 5
LEFT JOIN structure anc ON anc.structure_code = tr.anc_code
LEFT JOIN fm_version v ON v.version_id = bl.version_id
LEFT JOIN structure pc ON pc.structure_code = s.father_code
LEFT JOIN structure jv ON pc.father_code = jv.structure_code
AND jv.father_code <> 'Wbs138Root'
WHERE fa.account_type_code IN (#FundingType)
AND p.period_id BETWEEN #StartDate
AND #FinishDate
AND pe.code346 IN (#ActivePortfolio)
GROUP BY CASE
WHEN SUBSTRING(s.description, 13, 1) = '.'
THEN LEFT(s.description, 17)
ELSE LEFT(s.description, 12)
END
,pn.description
,pe.code346
,CASE
WHEN ast.Description = 'WAIO'
THEN anc.Description
ELSE site.Description
END
,CASE
WHEN SUBSTRING(jv.description, 5, 1) = ' '
THEN LEFT(jv.description, 4)
WHEN SUBSTRING(jv.description, 7, 1) = ' '
THEN LEFT(jv.description, 6)
ELSE jv.Description
END
,pe.code79
,pe.code390
,CAST(p.period_start AS DATE)
ORDER BY 1
,CAST(p.period_start AS DATE)
Try this:
SELECT CASE
WHEN SUBSTRING(s.description, 13, 1) = '.'
THEN LEFT(s.description, 17)
ELSE LEFT(s.description, 12)
END WBSCode
,pe.short_name
,pn.description ProjectName
,(
SELECT description
FROM structure
WHERE structure_code = pe.code346
) ActivePortfolio
,CASE
WHEN ast.Description = 'WAIO'
THEN anc.Description
ELSE site.Description
END SiteFunction
,CASE
WHEN SUBSTRING(jv.description, 5, 1) = ' '
THEN LEFT(jv.description, 4)
WHEN SUBSTRING(jv.description, 7, 1) = ' '
THEN LEFT(jv.description, 6)
ELSE jv.Description
END AS JointVenture
,(
SELECT description
FROM structure
WHERE structure_code = pe.code79
) AssetClassification
,(
SELECT description
FROM structure
WHERE structure_code = pe.code390
) InvestmentSize
,(
SELECT RIGHT(import_code, 6)
FROM structure
WHERE structure_code = pe.code79
) AssetClassCode
,CAST(p.period_start AS DATE) Period_Start
,SUM(CASE
WHEN be.currency_code = 'AUD'
AND #Currency = 'AUD'
THEN be.amount
WHEN be.currency_code = 'USD'
AND #Currency = 'USD'
THEN be.amount
WHEN be.currency_code = 'AUD'
AND #Currency = 'USD'
THEN be.amount * ip.pfn_exch_rate_on_date(p.period_start, be.currency_code)
WHEN be.currency_code = 'USD'
AND #Currency = 'AUD'
THEN be.amount * (ip.pfn_exch_rate_on_date(p.period_start, be.currency_code) / ip.pfn_exch_rate_on_date(p.period_start, 'AUD'))
END) Amount
FROM fm_budget_entry be
JOIN fm_period p ON be.period_id = p.period_id
JOIN fm_budget_line bl ON be.line_id = bl.line_id
AND bl.version_id = #FinancialVersion
JOIN fm_budget_line_attrib la ON la.line_id = bl.line_id
AND la.line_attrib_code = 'Wbs138'
JOIN structure s ON la.line_attrib_value = s.structure_code
JOIN fm_account fa ON bl.account_code = fa.account_code
JOIN planning_entity pe ON pe.planning_code = bl.structure_code
JOIN structure ast ON ast.structure_code = pe.code713
AND ast.Description IN (#Assets)
JOIN structure pn ON pn.structure_code = pe.planning_code
LEFT JOIN structure site ON site.structure_code = pe.code37
LEFT JOIN structure_tree tr ON tr.dsc_code = pe.planning_code
AND tr.anc_Depth = 5
LEFT JOIN structure anc ON anc.structure_code = tr.anc_code
LEFT JOIN fm_version v ON v.version_id = bl.version_id
LEFT JOIN structure pc ON pc.structure_code = s.father_code
LEFT JOIN structure jv ON pc.father_code = jv.structure_code
AND jv.father_code <> 'Wbs138Root'
WHERE fa.account_type_code IN (#FundingType)
AND p.period_id BETWEEN #StartDate
AND #FinishDate
AND pe.code346 IN (#ActivePortfolio)
GROUP BY CASE
WHEN SUBSTRING(s.description, 13, 1) = '.'
THEN LEFT(s.description, 17)
ELSE LEFT(s.description, 12)
END
,pe.short_name
,pn.description
,pe.code346
,CASE
WHEN ast.Description = 'WAIO'
THEN anc.Description
ELSE site.Description
END
,CASE
WHEN SUBSTRING(jv.description, 5, 1) = ' '
THEN LEFT(jv.description, 4)
WHEN SUBSTRING(jv.description, 7, 1) = ' '
THEN LEFT(jv.description, 6)
ELSE jv.Description
END
,pe.code79
,pe.code390
,CAST(p.period_start AS DATE)
ORDER BY 1
,CAST(p.period_start AS DATE)
I am having a view which returns value to a table. The process takes a long time... So I felt it works better if go for indexing on view. Can anyone plz guide me to add index to view.
ALTER View [dbo].[GetApplicationBudgetAndUtilized]
as
Select *, (convert(money,isnull(TotalBudget,0)) - convert(money,isnull(Utilized,0))) as [Left] from (
SELECT Distinct PM.PKID AS ProgramID, F.PKID as FundID, I.PKID as ProjectID,
MYB.PKID AS MultiYearBudgetID,
(Select Isnull(Sum(IsNull(PBC1.BudgetAmount,0)),0) from ProgramBudgetConfiguration PBC1
Where pbc1.MultiYearBgtIdFkId = pbc.MultiYearBgtIdFkId and PBC1.IsActive = 1 and LOVBudgetTypeIDFKID = 'BT_INC' group
by pbc1.MultiYearBgtIdFkId) AS TotalProgramBudget,
App.TotalBudget,
I.PKID,
(Case when exists (Select 'x' from InstallationTransactionHeader Where ParentPrjNumber = I.PKID and IsDelete = 0)
then
(case
when not exists (select cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)
from InstallationTransactionHeader I1 where I1.ParentPrjNumber is not null and I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and
I1.ParentPrjNumber = I.PKID and I1.FundRequestIDFKID is not null) then (select '0')
else
(select isnull(sum(cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)),0)
from InstallationTransactionheader I1 where I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and I1.ParentPrjNumber is not null and
I1.ParentPrjNumber = I.PKID and I1.isdelete = 0 and I1.FundRequestIDFKID is not null group by I1.parentPrjNumber)
End)
else
--isnull(cast(isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00) as Money),0)
(case
when not exists (select isnull(cast(isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00) as Money),0) from
InstallationTransactionHeader I where StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and IsDelete = 0 and
PKID = I.PKID and I.FundRequestIDFKID is not null) then 0--(select '0')
else
(select isnull(sum(cast(isnull(I1.CustInstallIncAmt,0.00) + isnull(I1.SPInstIncentiveAmt,0.00) + isnull(I1.ThirdPartyIncentive,0.00) as Money)),0)
from InstallationTransactionheader I1 where I1.StatusFKID in ('ITS_SUB','ITS_APP','ITS_VRF') and IsDelete = 0 and I1.FundRequestIDFKID is not null and
PKID = I.PKID)
End)
End) as Utilized
--Cast(App.TotalBudget - (isnull(I.CustInstallIncAmt,0.00) + isnull(I.SPInstIncentiveAmt,0.00) + isnull(I.ThirdPartyIncentive,0.00)) as Money) as [Left]
FROM
( SELECT PKID as FundID, ProgramID AS ProgramID, (ISNULL(IncentiveAmount,0.00) + ISNULL(CustInstallIncAmt, 0.00) + ISNULL(SPInstIncentiveAmt, 0.00) ) AS TotalBudget
FROM dbo.FundRequestHeader AS F WHERE (IsDelete = 0) AND (IsActive = 1) AND (StatusFKID in ('IAS_APP','IAS_CAN'))) AS App
INNER JOIN dbo.ProgramMaster AS PM
INNER JOIN dbo.MultiYearBudget AS MYB ON PM.PKID = MYB.ProgramIDFKID
INNER JOIN dbo.ProgramBudgetConfiguration AS PBC ON MYB.PKID = PBC.MultiYearBgtIdFkId ON App.ProgramID = PM.PKID
INNER JOIN dbo.FundRequestHeader AS F ON F.PKID = App.FundID
INNER JOIN dbo.InstallationTransactionHeader AS I ON I.FundRequestIDFKID = F.PKID
WHERE (PM.IsActive = 1) AND (MYB.IsActive = 1) AND (PBC.IsActive = 1) AND
(PBC.LOVBudgetTypeIDFKID = 'BT_INC') And (F.StatusFKID in ('IAS_APP','IAS_CAN'))
--and (1=case when(select ProgramTypeIDFKID from InstallationTransactionHEader where ProgramTypeIDFKID='IT_PRE' and ParentPrjNumber is null and PaymentSchedule=1)='IT_PRE' then 0 else 1 end)
--and I.ProgramTypeIDFKID <> 'IT_PRE' or I.PaymentSchedule = 0 or (I.ProgramTypeIDFKID = 'IT_PRE' and I.PaymentSchedule = 1 and I.ParentPrjNumber is not null)
and MYB.PKID = F.BudgetPeriodID and ((MYB.IsActive = 1))-- or ((MYB.status = 0) and F.StatusFKID ='IAS_APP'))
and (MYB.Status = 1 or (MYB.Status =(case when exists(select M.status from MultiYearBudget M, FundRequestHeader F
where F.ProgramID=M.ProgramIDFKID and F.ProgramTypeIDFKID <>'IT_FCFS' and M.Pkid=F.BudgetPeriodID
and F.StatusFKID='IAS_APP' and F.ProgramID=PM.PKID and M.Status=0 )then 0 else 1 end))
)
)temp
GO
Indexed views have certain limitations
In your case, I can immediately see some blockers
SELECT *
Derived tables
So read this article, and see how far you get...
However, you should be able to look the execution plan identify bottlenecks where you can add indexes to the bases tables