Need query to start at the beginning of the month - sql

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;

Related

Merge query in SQL Server stored procedure

I'll admit I don't have a lot of DB experience as my last job had a DBA but this place has none. I have an existing MASSIVE stored procedure that I need to modify (I noticed a lot of duplication and cut that out).
Right now, it pulls so much data they used a cache table or the page crashes. They just want a smaller amount of data now for a separate page. I'm trying to edit this stored procedure and merge in my new query to it.
The existing stored procedure:
ALTER PROCEDURE [dbo].[PurchasingSupplyChainNeeds]
(#maxAgeInHours INT = 24)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #sqlStmt NVARCHAR(max)
DECLARE #myName NVARCHAR(max) = Object_name(##PROCID)
DECLARE #needsRefresh INT
EXEC #needsRefresh = [cache].[NeedsRefresh]
#myName,
#maxAgeInHours
IF #needsRefresh = 1
BEGIN
DECLARE #CurrentMonth INT
DECLARE #DayOfWeek INT
DECLARE #EndOfWeekDate DATETIME
DECLARE #StartOfNextWeek DATETIME
DECLARE #WorkDaysInMonth INT
DECLARE #RunningDate DATE
DECLARE #WorkDaysLeftInMonth INT
DECLARE #DayOffset INT
SELECT #CurrentMonth = DATEPART(MONTH, GETDATE())
SELECT #DayOfWeek = DATEPART(WEEKDAY, GETDATE())
IF (#DayOfWeek = 1)
BEGIN
SET #StartOfNextWeek = GETDATE()
END
ELSE
BEGIN
SET #StartOfNextWeek = DATEADD(day, 8 - #DayOfWeek, GETDATE())
END
SELECT #DayOfWeek = DATEPART(weekday, GETDATE())
IF (#DayOfWeek = 7)
BEGIN
SET #EndOfWeekDate = Getdate()
END
ELSE
BEGIN
SET #EndOfWeekDate = DATEADD(day, -#DayOfWeek, GETDATE())
END
SET #WorkDaysInMonth = 0
SET #RunningDate = CONVERT(DATE, CONVERT(VARCHAR, #CurrentMonth) + '/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())))
WHILE ( Datepart(month, #RunningDate) = #CurrentMonth )
BEGIN
SET #DayOfWeek = Datepart(weekday, #RunningDate)
IF ( #DayOfWeek != 1
AND #DayOfWeek != 7 )
BEGIN
SET #WorkDaysInMonth = #WorkDaysInMonth + 1
END
SET #RunningDate = Dateadd(day, 1, #RunningDate)
END
SET #WorkDaysLeftInMonth = 0
SET #DayOffset = 0
WHILE ( Datepart(month, Dateadd(day, #DayOffset, Getdate())) = #CurrentMonth )
BEGIN
SET #DayOfWeek = Datepart(weekday, Dateadd(day, #DayOffset, Getdate()))
IF ( #DayOfWeek != 1
AND #DayOfWeek != 7 )
BEGIN
SET #WorkDaysLeftInMonth = #WorkDaysLeftInMonth + 1
END
SET #DayOffset = #DayOffset + 1
END;
WITH j
AS (SELECT Rtrim(Ltrim(imitmidx_sql.item_no)) AS ItemNo,
Rtrim(Ltrim(ISNULL(imitmidx_sql.item_desc_1, ''))) AS ItemDescription1,
Rtrim(Ltrim(ISNULL(imitmidx_sql.item_desc_2, ''))) AS ItemDescription2,
Rtrim(Ltrim(ISNULL(imitmidx_sql.activity_cd, '-'))) AS ActivityCode,
Rtrim(Ltrim(imitmidx_sql.pur_or_mfg)) AS PurchasedOrMfg,
Rtrim(Ltrim(ISNULL(imitmidx_sql.uom, '-'))) AS UOM,
/*
case statements ensure the price, avg_cost & price
are only observed from the item's primary location;
not secondary locations such as Amazon warehouses
*/
CASE
WHEN iminvloc_sql.loc = imitmidx_sql.loc THEN Rtrim(Ltrim(ISNULL(cicmpy.cmp_name, '')))
ELSE ''
END AS VendorName,
CASE
WHEN iminvloc_sql.loc = imitmidx_sql.loc THEN iminvloc_sql.avg_cost
ELSE 0
END AS AverageCost,
CASE
WHEN iminvloc_sql.loc = imitmidx_sql.loc THEN iminvloc_sql.price
ELSE 0
END AS Price,
iminvloc_sql.qty_on_hand AS QtyOnHand,
iminvloc_sql.qty_allocated AS QtyAllocated,
(SELECT ISNULL(qty_on_hand, 0)
FROM iminvloc_sql WITH (NOLOCK)
WHERE item_no = imitmidx_sql.item_no
AND loc = '3IV') AS QtyIn3IV,
(SELECT ISNULL(qty_on_hand, 0)
FROM iminvloc_sql WITH (NOLOCK)
WHERE item_no = imitmidx_sql.item_no
AND loc = '3TI') AS QtyIn3TI,
(SELECT ISNULL(qty_on_hand, 0)
FROM iminvloc_sql WITH (NOLOCK)
WHERE item_no = imitmidx_sql.item_no
AND loc = '3FA') AS QtyIn3FA,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -52, Cast(#EndOfWeekDate AS DATE))) AND Dateadd(week, -51, Cast(#EndOfWeekDate AS DATE))
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -52, Cast(#EndOfWeekDate AS DATE))) AND Dateadd(week, -51, Cast(#EndOfWeekDate AS DATE))) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesWeek1,
---Sales week 2 to 51 here
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -1, Cast(#EndOfWeekDate AS DATE))) AND #EndOfWeekDate
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Dateadd(day, 1, Dateadd(week, -1, Cast(#EndOfWeekDate AS DATE))) AND #EndOfWeekDate) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesWeek52,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -2, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE)
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -2, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE)) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesYear1,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE)
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Dateadd(year, -1, Getdate()))) AS DATE) AND Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE)) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesYear2,
(SELECT ISNULL(Sum(qty_ordered), 0)
FROM (SELECT y.qty_ordered
FROM oeordhdr_sql x WITH (NOLOCK)
INNER JOIN oeordlin_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE x.ord_type = 'O'
AND x.entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE) AND Cast(Getdate() AS DATE)
AND y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc
AND x.status != 'L'
UNION ALL
SELECT y.qty_to_ship
FROM (SELECT DISTINCT ord_type,
ord_no,
entered_dt
FROM oehdrhst_sql WITH (NOLOCK)
WHERE ord_type = 'O'
AND entered_dt BETWEEN Cast('1/1/' + CONVERT(VARCHAR, Datepart(year, Getdate())) AS DATE) AND Cast(Getdate() AS DATE)) x
INNER JOIN oelinhst_sql y WITH (NOLOCK)
ON x.ord_type = y.ord_type
AND x.ord_no = y.ord_no
WHERE y.item_no = imitmidx_sql.item_no
AND y.loc = iminvloc_sql.loc) s) AS SalesYTD,
CASE
WHEN Datediff(week, imitmidx_sql.activity_dt, Getdate()) > 52 THEN 52
ELSE Datediff(week, imitmidx_sql.activity_dt, Getdate())
END AS ActiveWeeks,
(SELECT ( ISNULL(ForecastQty, 0) / #WorkDaysInMonth ) * #WorkDaysLeftInMonth
FROM HP_PurchasingForecast
WHERE ItemNo = imitmidx_sql.item_no
AND [Month] = Datepart(month, Getdate())
AND [Year] = Datepart(year, Getdate())
AND Active = 1) AS RemainingForecastQty,
(SELECT ISNULL(ForecastQty, 0)
FROM HP_PurchasingForecast
WHERE ItemNo = imitmidx_sql.item_no
AND [Month] = Datepart(month, Getdate())
AND [Year] = Datepart(year, Getdate())
AND Active = 1) AS ForecastQty1,
---ForecastQty 2 to 11
(SELECT ISNULL(ForecastQty, 0)
FROM HP_PurchasingForecast
WHERE ItemNo = imitmidx_sql.item_no
AND [Month] = Datepart(month, Dateadd(month, 11, Getdate()))
AND [Year] = Datepart(year, Dateadd(month, 11, Getdate()))
AND Active = 1) AS ForecastQty12,
( (SELECT ISNULL(Sum(CASE
WHEN receipt_dt IS NULL THEN qty_ordered
ELSE qty_remaining
END), 0)
FROM poordlin_sql WITH (NOLOCK)
WHERE ord_status IN ( 'P', 'R' )
AND item_no = imitmidx_sql.item_no
AND promise_dt IS NOT NULL
AND promise_dt <= CONVERT(DATE, Dateadd(day, 6, #StartOfNextWeek))
AND
(
receipt_dt IS NULL
OR ISNULL(qty_remaining, 0) > 0
)
)
+ (SELECT ISNULL(Sum(y.quantity), 0)
FROM imtrnhdr_sql x WITH (NOLOCK)
INNER JOIN imtrndtl_sql y WITH (NOLOCK)
ON x.transit_no = y.transit_no
WHERE x.status IN ( 'A', 'S' )
AND y.item_no = imitmidx_sql.item_no
AND x.to_loc = iminvloc_sql.loc
AND x.due_date <= CONVERT(DATE, Dateadd(day, 6, #StartOfNextWeek))
AND NOT
(
x.from_loc = '3IV'
AND x.temp_loc = '3TI'
AND x.to_loc = iminvloc_sql.loc
)
) ) AS POQty1,
---POQty 2 to 52
( (SELECT ISNULL(Sum(CASE
WHEN receipt_dt IS NULL THEN qty_ordered
ELSE qty_remaining
END), 0)
FROM poordlin_sql WITH (NOLOCK)
WHERE ord_status IN ( 'P', 'R' )
AND item_no = imitmidx_sql.item_no
AND promise_dt IS NOT NULL
AND promise_dt BETWEEN CONVERT(DATE, Dateadd(day, 357, #StartOfNextWeek)) AND CONVERT(DATE, Dateadd(day, 363, #StartOfNextWeek))
AND
(
receipt_dt IS NULL
OR ISNULL(qty_remaining, 0) > 0
)
)
+ (SELECT ISNULL(Sum(y.quantity), 0)
FROM imtrnhdr_sql x WITH (NOLOCK)
INNER JOIN imtrndtl_sql y WITH (NOLOCK)
ON x.transit_no = y.transit_no
WHERE x.status IN ( 'A', 'S' )
AND y.item_no = imitmidx_sql.item_no
AND x.to_loc = iminvloc_sql.loc
AND x.due_date BETWEEN CONVERT(DATE, Dateadd(day, 357, #StartOfNextWeek)) AND CONVERT(DATE, Dateadd(day, 363, #StartOfNextWeek))
AND NOT
(
x.from_loc = '3IV'
AND x.temp_loc = '3TI'
AND x.to_loc = iminvloc_sql.loc
)
) ) AS POQty52
FROM imitmidx_sql imitmidx_sql WITH (NOLOCK)
LEFT OUTER JOIN iminvloc_sql iminvloc_sql WITH (NOLOCK)
ON imitmidx_sql.item_no = iminvloc_sql.item_no
AND
(
imitmidx_sql.loc = iminvloc_sql.loc /* Primary location for the item */
OR iminvloc_sql.loc = '3FA'/*Amazon Fullfillment Center*/
)
LEFT OUTER JOIN cicmpy cicmpy
ON iminvloc_sql.vend_no = cicmpy.cmp_code
AND cicmpy.cmp_type = 'S'),
i
AS (SELECT [ItemNo],
[ItemDescription1],
[ItemDescription2],
[ActivityCode],
[PurchasedOrMfg],
[UOM],
Max([VendorName]) [VendorName],
Max([AverageCost]) [AverageCost],
Max([Price]) [Price],
Sum([QtyOnHand]) [QtyOnHand],
Sum([QtyAllocated]) [QtyAllocated],
Max([QtyIn3IV]) [QtyIn3IV],
Max([QtyIn3TI]) [QtyIn3TI],
Max([QtyIn3FA]) [QtyIn3FA],
Sum([SalesWeek1]) [SalesWeek1],
---SalesWeek2 to 51
Sum([SalesWeek52]) [SalesWeek52],
Sum([SalesYear1]) [SalesYear1],
Sum([SalesYear2]) [SalesYear2],
Sum([SalesYTD]) [SalesYTD],
Avg([ActiveWeeks]) [ActiveWeeks],
Avg([RemainingForecastQty]) [RemainingForecastQty],
Avg([ForecastQty1]) [ForecastQty1],
---ForecastQty2 to 11
Avg([ForecastQty12]) [ForecastQty12],
Avg([POQty1]) [POQty1],
---POQty2 to 51
Avg([POQty52]) [POQty52]
FROM j
WHERE [PurchasedOrMfg] = 'M'
GROUP BY [ItemNo],
[ItemDescription1],
[ItemDescription2],
[ActivityCode],
[PurchasedOrMfg],
[UOM])
SELECT i.*,
CASE i.ActiveWeeks
WHEN 0 THEN 0
ELSE ( i.SalesWeek52 + i.SalesWeek51 + i.SalesWeek50 + i.SalesWeek49 + i.SalesWeek48 + i.SalesWeek47 ) /
(
CASE
WHEN i.ActiveWeeks < 6 THEN i.ActiveWeeks
ELSE 6
END
)
END AS Last6WeeksAvg,
CASE i.ActiveWeeks
WHEN 0 THEN 0
ELSE ( i.SalesWeek52 + i.SalesWeek51 + i.SalesWeek50 + i.SalesWeek49 + i.SalesWeek48 + i.SalesWeek47 + i.SalesWeek46 + i.SalesWeek45 + i.SalesWeek44 + i.SalesWeek43 + i.SalesWeek42 + i.SalesWeek41 ) /
(
CASE
WHEN i.ActiveWeeks < 12 THEN i.ActiveWeeks
ELSE 12
END
)
END AS Last12WeeksAvg,
CASE i.ActiveWeeks
WHEN 0 THEN 0
ELSE ( i.SalesWeek52 + i.SalesWeek51 + i.SalesWeek50 + i.SalesWeek49 + i.SalesWeek48 + i.SalesWeek47 + i.SalesWeek46 + i.SalesWeek45 + i.SalesWeek44 + i.SalesWeek43 + i.SalesWeek42 + i.SalesWeek41 + i.SalesWeek40 + i.SalesWeek39 + i.SalesWeek38 + i.SalesWeek37 + i.SalesWeek36 + i.SalesWeek35 + i.SalesWeek34 + i.SalesWeek33 + i.SalesWeek32 + i.SalesWeek31 + i.SalesWeek30 + i.SalesWeek29 + i.SalesWeek28 + i.SalesWeek27 + i.SalesWeek26 + i.SalesWeek25 + i.SalesWeek24 + i.SalesWeek23 + i.SalesWeek22 + i.SalesWeek21 + i.SalesWeek20 + i.SalesWeek19 + i.SalesWeek18 + i.SalesWeek17 + i.SalesWeek16 + i.SalesWeek15 + i.SalesWeek14 + i.SalesWeek13 + i.SalesWeek12 + i.SalesWeek11 + i.SalesWeek10 + i.SalesWeek9 + i.SalesWeek8 + i.SalesWeek7 + i.SalesWeek6 + i.SalesWeek5 + i.SalesWeek4 + i.SalesWeek3 + i.SalesWeek2 + i.SalesWeek1 ) / i.ActiveWeeks
END AS Last52WeeksAvg,
( ISNULL(i.RemainingForecastQty, 0) + ISNULL(i.ForecastQty2, 0) + ISNULL(i.ForecastQty3, 0) + ISNULL(i.ForecastQty4, 0) + ISNULL(i.ForecastQty5, 0) + ISNULL(i.ForecastQty6, 0) + ISNULL(i.ForecastQty7, 0) + ISNULL(i.ForecastQty8, 0) + ISNULL(i.ForecastQty9, 0) + ISNULL(i.ForecastQty10, 0) + ISNULL(i.ForecastQty11, 0) + ISNULL(i.ForecastQty12, 0) ) / 52 AS AvgWeeklyForecast,
ISNULL(i.QtyIn3FA, 0) + ISNULL(i.QtyOnHand, 0) + ISNULL(i.QtyIn3TI, 0) - ISNULL(i.QtyAllocated, 0) AS QtyAvailable
INTO #outputToCache
FROM i
SET #sqlStmt = 'select * INTO [cache].[' + #myName + '] from #outputToCache'
EXEC sp_executesql
#sqlStmt
END
SET #sqlStmt = 'select * from [cache].[' + #myName + ']'
EXEC sp_executesql
#sqlStmt
END
My query:
SELECT
tb_1.SubPart AS 'Sub Part',
SUM(tb_1.FinalItemSubPartQuantity) 'Sub Part Quantity Needed',
SUM(tb_1.FinalItemSubPartQuantity * tb_2.SalesWeek1) 'Total Sales Week 1',
--- Total Sales Week 2 to 51 here
SUM(tb_1.FinalItemSubPartQuantity * tb_2.SalesWeek52) 'Total Sales Week 52'
FROM
[009Reports].[dbo].[ANC Parts] tb_1
JOIN
[555].[cache].[PurchasingSupplyChainNeeds] tb_2 ON tb_1.FinalPartNo = tb_2.ItemNo
GROUP BY
tb_1.SubPart
Replacing this query below with mine:
AS (SELECT [ItemNo],
[ItemDescription1],
[ItemDescription2],
This is the error I get:
Msg 208, Level 16, State 1, Line 3168
Invalid object name 'i'
My query has 2 different tables in 2 different databases.
Currently, the stored procedure is using CTEs to create "temporary tables" based on (ugly and monstruous) queries and then use them to fill a table.
In general terms, a CTE is a table made from the results of a query, that's only usable by the immediate next query (this is: you create a CTE, then use it on a SELECT, INSERT, UPDATE... then the CTE gets destroyed).
What the SP is doing is this:
Creates CTE j using info and calculations from certain tables
Uses info from CTE j to create CTE i
Uses info from CTE i to create a temporary table #outputToCache
Dumps info from #outputToCache into a physical table cache.PurchasingSupplyChainNeeds
SELECTs and returns the info from cache.PurchasingSupplyChainNeeds as the resultset from the stored procedure
The error you're getting is because you're replacing the creation of CTE i with your own query, but i is still used later on to fill the temporary table.
Now, you say that what you are trying to achieve, is to retrieve a smaller amount of data from this last "cache" table for a separate page. IF I UNDERSTAND CORRECTLY (emphasized because I'm not 100% sure I got it already) you shouldn't modify this stored procedure (this is, add your query into it) because that would change the output of it, and would break anything that uses it. Not only that, your query is using info from the cache table, but the part you're trying to replace is what creates the CTE i that ultimately fills such table.
If what you really want to do is to change the resultset returned from this SP, then the query you need to replace with your own is the one that's assigned to the #sqlStmt variable at the end, so instead of
SET #sqlStmt = 'select * from [cache].[' + #myName + ']'
you would have
SET #sqlStmt = 'SELECT tb_1.SubPart AS [Sub Part], SUM(tb_1.FinalItemSubPartQuantity) [Sub Part Quantity Needed], SUM(tb_1.FinalItemSubPartQuantity * tb_2.SalesWeek1) [Total Sales Week 1],...'
*Note the change of quoted aliases to square-bracketed ones
If your query is meant to return information for a separate page, you should create another stored procedure with your query and then call this new SP from this separate page. This is of course if this cache table doesn't get emptied/deleted by a different process later on. If this is the case, then you're into a world of pain, as you would either need to duplicate this existing SP almost in its entirety into your new SP and change the output as stated above; add an optional parameter that determines wich output should this SP return (e.g. if the parameter is 1 the output is the same as now, but if the parameter is 2 the output is your query); or change this existing stored procedure to not return a value and make other(s) to calls this one and return information as needed. Probably the last option is the "least ugly" one.

Returning LINE with no inner join match

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 ....)

SQL Command Not Properly Ended

SELECT SUM(nvl(DYRCVDWT, 0)) + SUM(nvl(RCVDWT, 0)) + SUM(nvl(rcvdafpwt, 0)) - SUM(nvl(retdwt, 0)) INTO netwt
FROM YARNLEDGER yl
(SELECT D.PROFILECODE, MAX(CLOSINGDATE)SDATE FROM PARTYSTOCKCLOSING D WHERE D.DEPT = 'Y' AND NVL(D.POSTED, 'N') = 'Y' GROUP BY D.PROFILECODE) SAD
WHERE yl.PROFILECODE = :PROFILECODE
AND Yl.PROFILECODE = SAD.PROFILECODE(+)
AND Yl.DOCUMENTDATE>SAD.SDATE
there are missing a comma in the FROM after the "yarnledger yl"
SELECT SUM(nvl(dyrcvdwt, 0)) + SUM(nvl(rcvdwt, 0)) + SUM(nvl(rcvdafpwt, 0)) - SUM(nvl(retdwt, 0))
INTO netwt
FROM yarnledger yl ,(SELECT d.profilecode
,MAX(closingdate) sdate
FROM partystockclosing d
WHERE d.dept = 'Y'
AND nvl(d.posted, 'N') = 'Y'
GROUP BY d.profilecode) sad
WHERE yl.profilecode = :profilecode
AND yl.profilecode = sad.profilecode(+)
AND yl.documentdate > sad.sdate
next time use a clearer query structure:
WITH sad as (SELECT d.profilecode
,MAX(closingdate) sdate
FROM partystockclosing d
WHERE d.dept = 'Y'
AND nvl(d.posted, 'N') = 'Y'
GROUP BY d.profilecode)
SELECT SUM(nvl(dyrcvdwt, 0)) + SUM(nvl(rcvdwt, 0)) + SUM(nvl(rcvdafpwt, 0)) - SUM(nvl(retdwt, 0))
INTO netwt
FROM yarnledger yl
LEFT OUTER JOIN sad
ON yl.profilecode = sad.profilecode
AND yl.documentdate > sad.sdate
WHERE yl.profilecode = :profilecode

Performance Issue in Select groupby

I have following block of code and It takes approx 4-5 minutes to execute. All the tables in this block has large amount of data.
Select
spa.Student_Id,
Cast(Case When ISNULL(#PeriodNumbers, '') = '' Then --PeriodCode Come
CPS.PeriodIdentifier
Else --period number come
Cast(SPA.PeriodNumber as varchar)
End As varchar) As Period,
IsNULL(Count(*), 0) As TotalCount,
AC.ExcessiveAbsAttendanceType,
Cast(SPA.PeriodNumber as varchar) As PeriodNumber
From
(Select Student_ID
From OpenXml(#Handle,'/NewDataSet/Table', 2)
With (Student_ID int) As DT
) FilterDT
Inner Join
dbo.StudentPeriodicAttendanceArchive SPA WITH(NOLOCK) On FilterDT.Student_ID = SPA.Student_ID
Inner Join
dbo.AcademicYear AY WITH(NOLOCK) On AY.AYIdentifier = #AYIdentifier
And AY.School_Domain = #School_Domain
Inner join
dbo.CPsession CPS WITH(NOLOCK) On CPS.SSEC_ID = SPA.SSEC_ID
And CPS.PeriodNumber= spa.periodnumber
And CPS.School_Domain = #School_Domain
And CPS.AYIdentifier = #AYIdentifier
And (CPS.CPSDelStatus = 0 Or CPS.CPSDelStatus Is Null)
Inner Join
dbo.BellTimingScheduleStructure BTSS WITH(NOLOCK) ON BTSS.DayNumber = CPS.WD_ID
And BTSS.SchedulingWeek = CPS.Week
Inner Join
dbo.ClassPeriods CP WITH(NOLOCK) On CP.CP_Id = CPS.CP_ID
And BTSS.CPR_ID = CP.CPR_ID
And BTSS.WeekDay = Case When BTSS.CPRType='D' Then BTSS.WeekDay Else CP.WD_ID End
And BTSS.DayNumber = Case When BTSS.CPRType='D' Then CP.WD_ID Else BTSS.DayNumber End
And BTSS.SchedulingWeek = Case When BTSS.CPRType='W' Then BTSS.SchedulingWeek Else CP.Week End
And BTSS.DateItem = SPA.Attdate
And CP.CPDelStatus = '0'
And IsNull(CP.IsLocked, '0') = '0'
Inner Join
dbo.AttendanceCodes AC WITH(NOLOCK) On AC.AC_ID = SPA.AttCode_ID
Where
SPA.School_Domain = #School_Domain
And AttDate >= Case When #IsYearLongTotals=1 then AY.AYStartDate Else #ActualStartDate End
And AttDate <= Case When #IsYearLongTotals=1 then AY.AYEndDate Else #ActualEndDate End
And IsNull(#Subject_ID, -1) = Case When IsNull(#Subject_ID, -1) <> -1
Then CPS.Subject_ID
Else IsNull(#Subject_ID, -1)
End
Group By
spa.Student_ID,
Cast(Case When ISNULL(#PeriodNumbers, '') = ''
Then CPS.PeriodIdentifier
Else
Cast(SPA.PeriodNumber as varchar)
End As varchar), AC.ExcessiveAbsAttendanceType,
Cast(SPA.PeriodNumber as varchar)
I have a table StudentPeriodicAttendanceArchive which contains attendance information. I want to calculate total present and absent count.
Please suggest what should I do to improve the performance. I am using SQL Server 2008 R2

SQL TOP 1 issue when no record is found

Hope you can help me with this SQL issue I am unable to solve:
I have a price list file with multiple entries per item number like this:
ItemNo
ValidFrom
ValidTo
Price
Now when I try to generate a list with prices valid today, I use the statement below to get a decent report. I only have a problem when no valid price was found, i.e. for TODAY there is no record. In this case the first TOP 1 subquery still returns a (random?) value and destroys my report.
I assume that TOP 1 will always return one value by definition, or is there a trick which can prevent this?
Really appreciate your help! (and please excuse the german terms in the query...)
SELECT
MITBAL.MBITNO as 'Artikel', MITMAS.MMITDS as 'Bezeichnung',
MITBAL.MBBUYE as 'Disponent', MITMAS.MMNEWE as 'Gewicht',
MITBAL.MBSUNO as 'Lieferant', MMITTY as 'Typ',
m9ucos as 'Std.-Kosten', idsunm as 'Lieferantenname',
iicucd as 'WSL', MBEOQT as 'EOQ',
(select count(*)
from RCE12_Staging.dbo.mpagrl
left outer join RCE12_Staging.dbo.mpagrh on aicono = ahcono
and aiagnb = ahagnb and aisuno = ahsuno
where aicono = 2
and aiobv1 = mbitno and aisagl = 20
and aisuno between '400000' and '599999' and aigrpi = 40
and aiuvdt >= CONVERT(char(8), GETDATE(), 112) and ahpast = '40') as 'Anz.Lief',
(select TOP 1 ajpupr
from RCE12_Staging.dbo.mpagrp
left outer join RCE12_Staging.dbo.mpagrh on ajcono = ahcono
and ajagnb = ahagnb and ajsuno = ahsuno
left outer join RCE12_Staging.dbo.mpagrl on ajcono = aicono
and ajagnb = aiagnb and ajsuno = aisuno
where ajcono = 2
and ajobv1 = mbitno and ajsuno = mbsuno
and ajmapr = 1 and ajgrpi = 40
and ajfvdt < CONVERT(char(8), GETDATE(), 112) and ahpast = '40'
and ahfvdt < CONVERT(char(8), GETDATE(), 112)
and ahuvdt >= CONVERT(char(8), GETDATE(), 112)
and aisagl = 20 and aigrpi = 40
and aifvdt < CONVERT(char(8), GETDATE(), 112)
and aiuvdt >= CONVERT(char(8), GETDATE(), 112)
order by ajfvdt desc) as 'EK-Preis',
(select TOP 1 ajfrqt
from RCE12_Staging.dbo.mpagrp
left outer join RCE12_Staging.dbo.mpagrh on ajcono = ahcono
and ajagnb = ahagnb and ajsuno = ahsuno
left outer join RCE12_Staging.dbo.mpagrl on ajcono = aicono
and ajagnb = aiagnb and ajsuno = aisuno
where ajcono = 2 and ajobv1 = mbitno
and ajsuno = mbsuno and ajmapr = 1 and ajgrpi = 40
and ajfvdt < CONVERT(char(8), GETDATE(), 112) and ahpast = '40'
and ahfvdt < CONVERT(char(8), GETDATE(), 112)
and ahuvdt >= CONVERT(char(8), GETDATE(), 112) and aisagl = 20
and aigrpi = 40
and aifvdt < CONVERT(char(8), GETDATE(), 112)
and aiuvdt >= CONVERT(char(8), GETDATE(), 112)
order by ajfvdt desc) as 'EK-Menge'
FROM
RCE12_Staging.dbo.MITBAL MITBAL
left outer join
RCE12_Staging.dbo.MITFAC MITFAC ON mbcono = m9cono and mbitno = m9itno and m9faci = 'DFP'
left outer join
RCE12_Staging.dbo.MITMAS MITMAS ON mbcono = mmcono and mbitno = mmitno
left outer join
RCE12_Staging.dbo.CIDMAS CIDMAS ON mbcono = idcono and mbsuno = idsuno
left outer join
RCE12_Staging.dbo.CIDVEN CIDVEN ON mbcono = iicono and mbsuno = iisuno
WHERE
MITBAL.MBCONO = 2
AND MITBAL.MBWHLO = '200' AND MBSTAT = '20' AND MBPUIT = '2'
and MBITNO like '479200222%'
ORDER BY MBITNO
The 'top 1' will return the first row from the dataset if the dataset you have requested is empty then top 1 will return an empty dataset with no rows and no 'Random data'.
You should probably check the number of rows returned if you need the data for later in the query or initialise a variable and use that.