Merge many queries into one query to speed up - sql

I have written a procedure that collects data from 4 tables and issues a general report for the day.
There are two similar SQL queries in the procedure, the execution time of each of which is more than 1 seconds, respectively, the procedure execution time is more than 2 seconds, can this be optimized?
CREATE PROCEDURE cv
#dt AS SMALLDATETIME
AS
SELECT
(SELECT ISNULL(SUM(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0)
FROM RCassa
WHERE DataRC = #dt) AS crMagPDP,
(SELECT ISNULL(SUM(SumPrice), 0) -
ISNULL(SUM(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0)
FROM RCassa
WHERE DataRC = #dt) AS crMag,
for browse
2 queries are shown just as an example, there are more subqueries.
Whole procedure:
SET ANSI_NULLS OFF
SET QUOTED_IDENTIFIER OFF
GO
CREATE PROCEDURE CV
#dt as SMALLDATETIME
AS
SELECT
(SELECT isnull(sum(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0)
FROM RCassa WHERE DataRC = #dt) as crMagPDP,
(SELECT ISNULL(sum(SumPrice), 0) - isnull(sum(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0)
FROM RCassa WHERE DataRC = #dt) AS crMag,
(SELECT ISNULL(SUM(What_Done.Price_Sp), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Sp >= 0 AND What_Done.Nal <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Out_Date)) = #dt
) as crParts,
(SELECT ISNULL(SUM(What_Done.Price_Total - ISNULL(What_Done.Price_Diag, 0)), 0)
FROM What_Done INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total > 0 AND What_Done.Nal <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Out_Date)) = #dt
) + (SELECT ISNULL(SUM(What_Done.Price_Diag), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total >= 0 AND What_Done.Nal <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Order_Date)) = #dt
) as crCassa,
(SELECT ISNULL(SUM(What_Done.Price_Diag), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total >= 0 AND What_Done.Nal <> 0 AND What_Done.BCard_IN <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Order_Date)) = #dt
) + (SELECT ISNULL(SUM(What_Done.Price_Total - ISNULL(What_Done.Price_Diag, 0)), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total >= 0 AND What_Done.Nal <> 0 AND What_Done.BCard_OUT <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Out_Date)) = #dt
) as crBCard,
(SELECT ISNULL(SUM(Summ), 0) FROM RevOrd WHERE Summ >= 0 AND Nal <> 0 AND DateOrd = #dt) as crNal,
(SELECT ISNULL(SUM(Summ), 0) FROM RevOrd WHERE Summ >= 0 AND Nal = 0 AND DateOrd = #dt) as crCard,
(SELECT ISNULL(Sum(SumTotal), 0) FROM LineOrders WHERE DataOut = #dt) as crLine,
(SELECT ISNULL(Sum(SumTotal), 0) FROM LineOrders WHERE DataOut = #dt and Dost <> 0) as crDostavka,
(SELECT ISNULL(SUM(What_Done.BCard_IN_Sum), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total >= 0 AND What_Done.Nal <> 0 AND What_Done.BCard_IN <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Order_Date)) = #dt
)+(SELECT ISNULL(SUM(What_Done.BCard_OUT_Sum), 0)
FROM What_Done
INNER JOIN ORDERS ON What_Done.uid = ORDERS.uid
WHERE What_Done.Price_Total >= 0 AND What_Done.Nal <> 0 AND What_Done.BCard_OUT <> 0
AND CONVERT(datetime, CONVERT(varchar(12), ORDERS.Out_Date)) = #dt
) as crBCardCorrect
for browse

Assuming the criteria for the sub-queries are identical and filter on DataRC = #dt and use the same data source RCassa, then you can simplify the query like this:
SELECT
isnull(sum(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0) as crMagPDP,
ISNULL(sum(SumPrice), 0) - isnull(sum(CASE WHEN PrePayDate IS NULL THEN '0' ELSE Price * Kvo END), 0) AS crMag,
...
FROM RCassa
WHERE DataRC = #dt

If the outer select is from other table[s] use APPLY
SELECT
isnull(t.crMagPDP, 0) crMagPDP,
isnull(t.crMag, 0) crMag,
..
FROM
..
OUTER APPLY (
SELECT
sum(CASE WHEN PrePayDate IS NULL THEN 0 ELSE Price * Kvo END) as crMagPDP,
sum(SumPrice) - sum(CASE WHEN PrePayDate IS NULL THEN 0 ELSE Price * Kvo END) AS crMag,
...
FROM RCassa
WHERE DataRC = #dt
) t

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.

The multi-part identifier 'dbo.AdditionalInfo.UserDefined3' could not be bound

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

MSSQL Case Where Clause

i have the following query.
SELECT DISTINCT datepart(day, eventdetails_datetime) as dates , bu_events.event_daysbeforeType
FROM "bu_events"
INNER JOIN "bu_eventdetails" ON "bu_eventdetails"."event_id" = "bu_events"."event_id"
WHERE "bu_events"."is_active" = 1
AND "bu_events"."is_deleted" =0
AND "bu_eventdetails"."is_active" = 1
AND "bu_eventdetails"."is_deleted" =0
AND "bu_events"."service_id" = '31'
AND (DATEDIFF(Minute, BU_EventDetails.eventDetails_datetime, '2017-07-12 10:33:19') <=0 or coalesce(event_always_available,0) = 1 )
AND
(DATEDIFF(d, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
AND ( select max(availabletable_amount)
from bu_availabletable
inner join bu_eventdetails on bu_eventdetails.eventdetail_id = bu_availabletable.eventdetail_id
inner join bu_eventpricegroups on bu_eventpricegroups.event_id = bu_eventdetails.event_id
where bu_availabletable.eventdetail_id = bu_eventdetails.eventdetail_id
and bu_eventpricegroups.eventpricegroup_always_available = 0 ) > 0
AND datepart(Month,eventdetails_datetime) = 07
AND datediff(d,getdate(),eventdetails_datetime)>=0
What i'm trying to do, is if bu_events.event_daysbeforeType is 1 then (DATEDIFF(d, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 ) and if it's 2 then (DATEDIFF(hour, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
So depending on bu_events.event_daysbeforeType i want to datediff with D or HOUR.
What i've tried so far but not working is this:
SELECT DISTINCT datepart(day, eventdetails_datetime) as dates , bu_events.event_daysbeforeType
FROM "bu_events"
INNER JOIN "bu_eventdetails" ON "bu_eventdetails"."event_id" = "bu_events"."event_id"
WHERE "bu_events"."is_active" = 1
AND "bu_events"."is_deleted" =0
AND "bu_eventdetails"."is_active" = 1
AND "bu_eventdetails"."is_deleted" =0
AND "bu_events"."service_id" = '31'
AND (DATEDIFF(Minute, BU_EventDetails.eventDetails_datetime, '2017-07-12 10:33:19') <=0 or coalesce(event_always_available,0) = 1 )
AND
CASE
WHEN bu_events.event_daysbeforeType = 1 THEN
(DATEDIFF(d, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
ELSE
(DATEDIFF(hour, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
END
AND ( select max(availabletable_amount)
from bu_availabletable
inner join bu_eventdetails on bu_eventdetails.eventdetail_id = bu_availabletable.eventdetail_id
inner join bu_eventpricegroups on bu_eventpricegroups.event_id = bu_eventdetails.event_id
where bu_availabletable.eventdetail_id = bu_eventdetails.eventdetail_id
and bu_eventpricegroups.eventpricegroup_always_available = 0 ) > 0
AND datepart(Month,eventdetails_datetime) = 07
AND datediff(d,getdate(),eventdetails_datetime)>=0
Any ideas what i'm doing wrong ?
You can't use case like you this. case is an expression, and you try to use it as flow control.
From MSDN:
The CASE expression cannot be used to control the flow of execution of Transact-SQL statements, statement blocks, user-defined functions, and stored procedures. For a list of control-of-flow methods, see Control-of-Flow Language (Transact-SQL).
Instead of using case, do this:
AND
(
(
bu_events.event_daysbeforeType = 1
AND (DATEDIFF(d, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
)
OR
(
bu_events.event_daysbeforeType <> 1
AND (DATEDIFF(hour, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime) >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1 )
)
)
CASE is for computing the value and as SQL has no logical (boolean) values it shouldn't be mixed up with logical expressions but a computed value is a valid argument of logical expression. Try
AND (CASE WHEN bu_events.event_daysbeforeType = 1
THEN (DATEDIFF(d, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime)
ELSE DATEDIFF(hour, '2017-07-12 10:33:19',BU_EventDetails.eventDetails_datetime)
END >= coalesce(BU_Events.event_daysbefore, 0) or coalesce(event_always_available,0) = 1
)

Why if I put extra space or comment out a column from SELECT statement - all query run slower

Weird thing happening.
Query below runs less than a second, but if I change anything(like extra space) in WHERE clause then the whole query running 7 seconds.
Or if I comment out one of those lines (SELECT ISNULL(SUM(...) ...
Never see that before...
SELECT...
...
FROM ...
--If I put extra space after SELECT - the whole query running 7 seconds
WHERE EXISTS
(SELECT * FROM tblClaims_ReservePayments RP
WHERE
CASE WHEN #coverageTypeId IS NULL THEN 1
ELSE
CASE WHEN RP.CoverageTypeId = #coverageTypeId THEN 1 ELSE 0 END END = 1
AND (DATEDIFF(d, #dateFrom, RP.DateCreated) >= 0 AND DATEDIFF(d, #dateTo, RP.DateCreated) <= 0) AND RP.ClaimId = C.ClaimId)
AND
CASE WHEN #companyGuid IS NULL THEN 1 ELSE CASE WHEN CPI.CompanyGuid = #companyGuid THEN 1 ELSE 0 END END = 1
AND
EXISTS (SELECT * FROM tblClaims_Claimants CLMNT WHERE CLMNT.ClaimID = C.ClaimID AND CLMNT.StatusId = 0)
AND EXISTS (SELECT * FROM #Adjusters WHERE adjuster = C.InhouseAdjuster)
ORDER BY
CPI.PolicyNumber
What is going on?
Is it parameter sniffing?
The whole statement is below:
DECLARE
#dateFrom DATETIME = '2017-02-01',
#dateTo DATETIME = '2017-05-31',
#companyGuid UNIQUEIDENTIFIER = 'A95645F7-74CF-4551-BD28-5CBC5AD77EF2',-- NULL, Philadelphia
#coverageTypeId INT = NULL,
#inhouseAdjuster varchar(8000) = NULL
DECLARE #Adjusters TABLE(adjuster uniqueidentifier)
IF(#inhouseAdjuster IS NOT NULL AND #inhouseAdjuster <> '')
BEGIN
INSERT INTO #Adjusters
SELECT Guid FROM dbo.StringOfGuidsToTable(#inhouseAdjuster, ',')
END
ELSE
BEGIN
INSERT INTO #Adjusters
SELECT InhouseAdjuster FROM tblClaims_Claim
END
DECLARE #AdjusterString varchar(500)
SET #AdjusterString = ''
DECLARE #CoveringTable TABLE (Covering varchar(1000))
INSERT INTO #CoveringTable
SELECT DISTINCT tblUsers.FirstName + ' ' + tblUsers.LastName FROM tblClaims_Claim
inner join tblUsers on tblUsers.userguid = tblClaims_Claim.userguid
WHERE tblClaims_Claim.InhouseAdjuster IN (SELECT adjuster FROM #Adjusters)
SELECT #AdjusterString = #AdjusterString + CASE WHEN #AdjusterString = '' THEN '' ELSE ', ' END + Covering FROM #CoveringTable
SELECT
CPI.PolicyNumber,
CC.DateReported,--------------------------------------added by Oleg 5/1/2017
C.LossDate as ForfeitureDate,
(SELECT ISNULL(SUM(ResPayAmount), 0) FROM tblClaims_ReservePayments RP INNER JOIN lstClaims_ReservePaymentTypes RPT ON RPT.ResPayTypeId = RP.ResPayTypeId AND RPT.ResPayTypedescription <> 'Expense' WHERE RP.ClaimId = C.ClaimId AND (DATEDIFF(d, #dateFrom, RP.DateCreated) >= 0 AND DATEDIFF(d, #dateTo, RP.DateCreated) <= 0) AND CASE WHEN #coverageTypeId IS NULL THEN 1 ELSE CASE WHEN RP.CoverageTypeId = #coverageTypeId THEN 1 ELSE 0 END END = 1) AS [BondAmount],
dbo.GetEntityName(CPI.InsuredGuid) as Defendant,
CC.UserDef_ClaimantId as CaseNumber,
CC.CorporationName, -----------------------------------------------------------------------------------------------------------------------added by Oleg 5/1/2017
PRIM_ADDRESS.City,-----------------------------------------------------------------------------------------------------------------------added by Oleg 5/1/2017
PRIM_ADDRESS.State,-----------------------------------------------------------------------------------------------------------------------added by Oleg 5/1/2017
PRIM_ADDRESS.County,-----------------------------------------------------------------------------------------------------------------------added by Oleg 5/1/2017
(SELECT ISNULL(SUM(ResPayAmount), 0) FROM tblClaims_ReservePayments RP INNER JOIN lstClaims_ReservePaymentTypes RPT ON RPT.ResPayTypeId = RP.ResPayTypeId AND RPT.ResPayTypedescription <> 'Expense' WHERE RP.ClaimId = C.ClaimId AND IsPayment = 1 AND (DATEDIFF(d, #dateFrom, RP.DateCreated) >= 0 AND DATEDIFF(d, #dateTo, RP.DateCreated) <= 0) AND CASE WHEN #coverageTypeId IS NULL THEN 1 ELSE CASE WHEN RP.CoverageTypeId = #coverageTypeId THEN 1 ELSE 0 END END = 1) AS [ClaimsPaid],
(SELECT ISNULL(SUM(ResPayAmount), 0) FROM tblClaims_ReservePayments RP INNER JOIN lstClaims_ReservePaymentTypes RPT ON RPT.ResPayTypeId = RP.ResPayTypeId AND RPT.ResPayTypedescription <> 'Expense' WHERE RP.ClaimId = C.ClaimId AND IsPayment = 0 AND (DATEDIFF(d, #dateFrom, RP.DateCreated) >= 0 AND DATEDIFF(d, #dateTo, RP.DateCreated) <= 0) AND CASE WHEN #coverageTypeId IS NULL THEN 1 ELSE CASE WHEN RP.CoverageTypeId = #coverageTypeId THEN 1 ELSE 0 END END = 1) AS [ClaimsReserveRemaining],
(SELECT ISNULL(SUM(ResPayAmount), 0) FROM tblClaims_ReservePayments RP INNER JOIN lstClaims_ReservePaymentTypes RPT ON RPT.ResPayTypeId = RP.ResPayTypeId AND RPT.ResPayTypedescription = 'Expense' WHERE RP.ClaimId = C.ClaimId AND (DATEDIFF(d, #dateFrom, RP.DateCreated) >= 0 AND DATEDIFF(d, #dateTo, RP.DateCreated) <= 0)AND CASE WHEN #coverageTypeId IS NULL THEN 1 ELSE CASE WHEN RP.CoverageTypeId = #coverageTypeId THEN 1 ELSE 0 END END = 1) AS [AllocatedReserved],
(SELECT ISNULL(SUM(ResPayAmount), 0) FROM tblClaims_ReservePayments RP INNER JOIN lstClaims_ReservePaymentTypes RPT ON RPT.ResPayTypeId = RP.ResPayTypeId AND RPT.ResPayTypedescription = 'Expense' WHERE RP.ClaimId = C.ClaimId AND IsPayment = 1 AND (DATEDIFF(d, #dateFrom, RP.DateCreated) >= 0 AND DATEDIFF(d, #dateTo, RP.DateCreated) <= 0) AND CASE WHEN #coverageTypeId IS NULL THEN 1 ELSE CASE WHEN RP.CoverageTypeId = #coverageTypeId THEN 1 ELSE 0 END END = 1) AS [AllocatedPaid],
(SELECT ISNULL(SUM(ResPayAmount), 0) FROM tblClaims_ReservePayments RP INNER JOIN lstClaims_ReservePaymentTypes RPT ON RPT.ResPayTypeId = RP.ResPayTypeId AND RPT.ResPayTypedescription = 'Expense' WHERE RP.ClaimId = C.ClaimId AND IsPayment = 0 AND (DATEDIFF(d, #dateFrom, RP.DateCreated) >= 0 AND DATEDIFF(d, #dateTo, RP.DateCreated) <= 0) AND CASE WHEN #coverageTypeId IS NULL THEN 1 ELSE CASE WHEN RP.CoverageTypeId = #coverageTypeId THEN 1 ELSE 0 END END = 1) AS [AllocatedReserveRemaining],
(SELECT ISNULL(SUM(Amount), 0) FROM tblClaims_ClaimExpenses CE WHERE CE.ClaimId = C.ClaimId AND (DATEDIFF(d, #dateFrom, CE.DateEntered) >= 0 AND DATEDIFF(d, #dateTo, CE.DateEntered) <= 0)) AS [UnAllocated]
FROM
tblClaims_Claim C
INNER JOIN
tblClaims_PolicyInformation CPI
ON
CPI.ClaimId = C.ClaimId
INNER JOIN tblClaims_Claimants CC ON C.ClaimId = CC.ClaimId --AND CC.StatusId = 0 -----------------------------------added by Oleg 5/1/2017
INNER JOIN tblClaims_Addresses PRIM_ADDRESS ON PRIM_ADDRESS.AddressId = CC.AddressId ----------------------------------added by Oleg 5/1/2017
CROSS APPLY (SELECT TOP 1 QuoteGUID FROM tblQuotes WHERE tblQuotes.ControlNo = C.ControlNo) t ------------------------added by Oleg 5/1/2017
WHERE EXISTS
(SELECT * FROM tblClaims_ReservePayments RP
WHERE
CASE WHEN #coverageTypeId IS NULL THEN 1
ELSE
CASE WHEN RP.CoverageTypeId = #coverageTypeId THEN 1 ELSE 0 END END = 1
AND (DATEDIFF(d, #dateFrom, RP.DateCreated) >= 0 AND DATEDIFF(d, #dateTo, RP.DateCreated) <= 0) AND RP.ClaimId = C.ClaimId)
AND
CASE WHEN #companyGuid IS NULL THEN 1 ELSE CASE WHEN CPI.CompanyGuid = #companyGuid THEN 1 ELSE 0 END END = 1
AND
EXISTS (SELECT * FROM tblClaims_Claimants CLMNT WHERE CLMNT.ClaimID = C.ClaimID AND CLMNT.StatusId = 0)
AND EXISTS (SELECT * FROM #Adjusters WHERE adjuster = C.InhouseAdjuster)
ORDER BY
CPI.PolicyNumber
UPDATE:
If i put extra space in any line - it changes the performance to 7 sec.
When a query is run, SQL Server compiles it into a query plan.
In order to match the same SQL query to this plan, the database generates a hash code for the query (called a "query hash") based on the query text.
If you change the query in any way-- even seemingly safe things like capitalization (where this does not affect the query), add spaces, add comments-- the query text is now different. SQL Server will generate a different query hash for the query.
Given a new query hash, an existing query plan for this query hash will not be found. Therefore the SQL optimizer will create a new query plan. The new query plan is most likely very different than the old one-- possibly from parameter sniffing, as you suggested.
Commenting out functional parts of the query does actually change the query. For example, commenting out a single line in a SELECT clause can drastically alter the performance of the query, because now SQL Server may not need that column from the table. This means it could select a different index or skip a bookmark lookup, so performance can radically change.

not able call alias column name in where condition in sql server

WITH cte1
AS (SELECT
tbl.EmpID,
CASE
WHEN MIN(tbl.LeaveTypeId) = 'a' THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'Absent',
CASE
WHEN (MIN(tbl.LeaveTypeId) IS NOT NULL OR
MIN(tbl.LeaveTypeId) <> '') THEN MIN(tbl.LeaveDesc)
ELSE NULL
END AS 'Leave',
CASE
WHEN (MIN(tbl.outime) IS NULL) AND
(MIN(tbl.LeaveTypeId) IS NULL) THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'InOut',
CASE
WHEN CONVERT(char(5), MIN(tbl.InTime), 108) <> '00:00' THEN MIN(tbl.InTime)
ELSE NULL
END AS 'S1IN',
MIN(tbl.outime) AS 'S1OUT',
CASE
WHEN MIN(tbl.InTime) = MAX(tbl.InTime) THEN NULL
ELSE MAX(tbl.InTime)
END AS 'S2IN',
CASE
WHEN MIN(tbl.outime) = MAX(tbl.outime) THEN NULL
ELSE MAX(tbl.outime)
END AS 'S2OUT',
CASE
WHEN MIN(tbl.InTime) > DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))) THEN DATEDIFF(n, DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))), MIN(InTime))
ELSE 0
END AS 'LateBy',
CASE
WHEN MAX(tbl.OuTime) < DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))) THEN DATEDIFF(n, MAX(OuTime), DATEADD(dd, 0, DATEDIFF(dd, 0, MAX(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))))
ELSE 0
END AS 'EarlyBy',
MIN(emp.EmpFullName) AS 'EmpFullName',
MIN(tbl.P_Date) AS 'P_Date',
MIN(emp.nation_id) AS 'nation_id',
MIN(emp.dept_id) AS 'dept_id',
MIN(emp.desig_id) AS 'designation_id',
MIN(emp.tradecd) AS 'tradecd',
MIN(emp.comp_id) AS 'comp_id',
MIN(emp.section_id) AS 'section_id',
MIN(emp.location_id) AS 'location_id',
MIN(emp.emplcatgry) AS 'emplcatgry',
(SELECT
HODName
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptHOD',
(SELECT
HODEmail
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptEmail',
(SELECT
ManagerName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocManager',
(SELECT
Email
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocEmail',
(SELECT
LocationName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Location',
(SELECT
LocType
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocType',
(SELECT
MinWorkingHour
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Minworkhr'
FROM tblattendance tbl
INNER JOIN employees emp
ON emp.empid = tbl.empid
INNER JOIN Company cmp
ON cmp.comp_id = emp.comp_id
INNER JOIN ShiftDetails sd
ON emp.ShiftCode = ISNULL((SELECT
ShiftCode
FROM Shift_Calender
WHERE nFingerPrintId = emp.empid
AND C_Date = tbl.p_date)
, sd.ShiftCode)
AND sd.DayOfWeek = DATENAME(dw, tbl.p_date)
WHERE CONVERT(varchar(10), tbl.p_date, 112) BETWEEN '20151101' AND '20151101'
AND emp.status <> 'terminated'
GROUP BY tbl.p_date,
tbl.EmpID)
SELECT
*,
CASE
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NOT NULL AND
S2OUT IS NOT NULL THEN DATEDIFF(n, S1IN, S1OUT) + DATEDIFF(n, S2IN, S2OUT)
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NULL AND
S2OUT IS NULL THEN DATEDIFF(n, S1IN, S1OUT)
ELSE 0
END AS 'TotalHrs'
FROM cte1
WHERE (Absent = 1
OR InOut = 1
OR LateBy > 0
OR EarlyBy > 0)
AND LocType = 'Retail Store'
AND Location =
CASE 'Lite N Lamps'
WHEN '0' THEN Location
ELSE 'Lite N Lamps'
END
n this query i want to add one more condition like
AND LocType = 'Retail Store' and TotalHrs=0 but showing error
Invalid column name 'TotalHrs'.
How i can resolve this issue.if any help is very appreciable,thanks in advance
You can use multiple CTE's in following:
WITH cte1
AS (SELECT
tbl.EmpID,
CASE
WHEN MIN(tbl.LeaveTypeId) = 'a' THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'Absent',
CASE
WHEN (MIN(tbl.LeaveTypeId) IS NOT NULL OR
MIN(tbl.LeaveTypeId) <> '') THEN MIN(tbl.LeaveDesc)
ELSE NULL
END AS 'Leave',
CASE
WHEN (MIN(tbl.outime) IS NULL) AND
(MIN(tbl.LeaveTypeId) IS NULL) THEN CONVERT(bit, 1)
ELSE CONVERT(bit, 0)
END AS 'InOut',
CASE
WHEN CONVERT(char(5), MIN(tbl.InTime), 108) <> '00:00' THEN MIN(tbl.InTime)
ELSE NULL
END AS 'S1IN',
MIN(tbl.outime) AS 'S1OUT',
CASE
WHEN MIN(tbl.InTime) = MAX(tbl.InTime) THEN NULL
ELSE MAX(tbl.InTime)
END AS 'S2IN',
CASE
WHEN MIN(tbl.outime) = MAX(tbl.outime) THEN NULL
ELSE MAX(tbl.outime)
END AS 'S2OUT',
CASE
WHEN MIN(tbl.InTime) > DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))) THEN DATEDIFF(n, DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, MIN(sd.S1SL), MIN(sd.S1Start)))), MIN(InTime))
ELSE 0
END AS 'LateBy',
CASE
WHEN MAX(tbl.OuTime) < DATEADD(dd, 0, DATEDIFF(dd, 0, MIN(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))) THEN DATEDIFF(n, MAX(OuTime), DATEADD(dd, 0, DATEDIFF(dd, 0, MAX(tbl.P_Date))) + ' ' + CONVERT(varchar(10), CONVERT(time, DATEADD(n, -MIN(sd.S2EL), MIN(sd.S2End)))))
ELSE 0
END AS 'EarlyBy',
MIN(emp.EmpFullName) AS 'EmpFullName',
MIN(tbl.P_Date) AS 'P_Date',
MIN(emp.nation_id) AS 'nation_id',
MIN(emp.dept_id) AS 'dept_id',
MIN(emp.desig_id) AS 'designation_id',
MIN(emp.tradecd) AS 'tradecd',
MIN(emp.comp_id) AS 'comp_id',
MIN(emp.section_id) AS 'section_id',
MIN(emp.location_id) AS 'location_id',
MIN(emp.emplcatgry) AS 'emplcatgry',
(SELECT
HODName
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptHOD',
(SELECT
HODEmail
FROM Department
WHERE Dept_id = MIN(emp.dept_id))
AS 'deptEmail',
(SELECT
ManagerName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocManager',
(SELECT
Email
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocEmail',
(SELECT
LocationName
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Location',
(SELECT
LocType
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'LocType',
(SELECT
MinWorkingHour
FROM Location
WHERE Location_id = MIN(emp.location_id))
AS 'Minworkhr'
FROM tblattendance tbl
INNER JOIN employees emp
ON emp.empid = tbl.empid
INNER JOIN Company cmp
ON cmp.comp_id = emp.comp_id
INNER JOIN ShiftDetails sd
ON emp.ShiftCode = ISNULL((SELECT
ShiftCode
FROM Shift_Calender
WHERE nFingerPrintId = emp.empid
AND C_Date = tbl.p_date)
, sd.ShiftCode)
AND sd.DayOfWeek = DATENAME(dw, tbl.p_date)
WHERE CONVERT(varchar(10), tbl.p_date, 112) BETWEEN '20151101' AND '20151101'
AND emp.status <> 'terminated'
GROUP BY tbl.p_date,
tbl.EmpID)
, cte2 AS
(
SELECT
*,
CASE
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NOT NULL AND
S2OUT IS NOT NULL THEN DATEDIFF(n, S1IN, S1OUT) + DATEDIFF(n, S2IN, S2OUT)
WHEN S1IN IS NOT NULL AND
S1OUT IS NOT NULL AND
S2IN IS NULL AND
S2OUT IS NULL THEN DATEDIFF(n, S1IN, S1OUT)
ELSE 0
END AS 'TotalHrs'
FROM cte1
WHERE (Absent = 1
OR InOut = 1
OR LateBy > 0
OR EarlyBy > 0)
AND LocType = 'Retail Store'
AND Location =
CASE 'Lite N Lamps'
WHEN '0' THEN Location
ELSE 'Lite N Lamps'
END
)
SELECT *
FROM cte2
WHERE TotalHrs=0 --your alias condition or you can move all where clause here