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
Related
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.
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 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
I have taken over the support of an Excel 2010 macro and need to change the sort order of a recordset.
The query below worked before I attempted to change the order by adding rl.list_order.
Now I'm getting the error "The multi-part identifier could not be bound" and have tried many alternatives and have researched on this site for a solution but haven't been able to solve this. Can someone please help.
SELECT ips_rc.project, lfbe.Category, ips_rc.roster_id, ips_rc.role_category, ips_rc.role_title AS Role, ips_rc.role_code, ips_rc.role_title + ' (' + ips_rc.role_code + ')' AS PS_Role, CASE WHEN ISNULL(lfbe.Pronto_Role_Code, '') = '' THEN 'TO_BE_MAPPED' ELSE ISNULL(lfbe.Pronto_Role_Code, '') END AS Pronto_Role_Code, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Description, '') = '' THEN ips_rc.role_title ELSE ISNULL(lfbe.Pronto_Role_Code_Description, '') END AS Pronto_Role_Code_Description, ISNULL(lfbe.Rate, 0) AS Rate, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Old, '') = '' THEN ips_rc.role_title ELSE lfbe.Pronto_Role_Code_Old END AS Pronto_Role_Code_Old, CASE WHEN ISNULL(lfbe.Pronto_Role_Code_Description_Old, '') = '' THEN 'TO_BE_MAPPED' ELSE lfbe.Pronto_Role_Code_Description_Old END AS Pronto_Role_Code_Description_Old, ips_rc.Shift, ips_rc.UOM, ips_rc.Date, ips_rc.DHours, ips_rc.NHours FROM (SELECT psrc.project, pr_jcm.customer, pr_jcm.subcode, psrc.roster_id, psrc.role_id, psrc.role_category, psrc.role_title,
psrc.role_code, CASE WHEN SUM(CASE WHEN psrc.Date BETWEEN psrc.start_date AND psrc.end_date THEN psrc.NWorkHours ELSE 0 END) OVER (PARTITION BY psrc.project, psrc.roster_id) >= SUM(CASE WHEN psrc.Date BETWEEN psrc.start_date AND psrc.end_date THEN psrc.DWorkHours ELSE 0 END) OVER (PARTITION BY psrc.project, psrc.roster_id) THEN 'Night Shifts' ELSE 'Day Shifts' END AS Shift, 'HOURS' AS UOM, psrc.Date, psrc.DHours, psrc.NHours FROM (SELECT rcd.project, rcd.start_date, rcd.end_date, rcd.roster_id, rcd.role1_id AS role_id, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.category WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.category WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.category ELSE rcd.role_category END AS role_category, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.title WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.title WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.title ELSE rcd.role_title END AS role_title, CASE WHEN rb_test1.role1_id IS NOT NULL THEN CAST(rb_test1.band_r
ole_id AS VARCHAR) WHEN rb_test2.role1_id IS NOT NULL THEN CAST(rb_test2.band_role_id AS VARCHAR) WHEN rb_test3.role1_id IS NOT NULL THEN CAST(rb_test3.band_role_id AS VARCHAR) ELSE rcd.role_code END AS role_code, rcd.shift_date AS Date, SUM(CASE WHEN rcd.shift_ampm = 'day' THEN rcd.shift_time ELSE 0 END) AS DHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'work' THEN rcd.shift_time ELSE 0 END) AS DWorkHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'eqmob' THEN rcd.shift_time ELSE 0 END) AS DEqmobHours, SUM(CASE WHEN rcd.shift_ampm = 'day' AND rcd.shift_type = 'eqdemob' THEN rcd.shift_time ELSE 0 END) AS DEqdemobHours, SUM(CASE WHEN rcd.shift_ampm = 'night' THEN rcd.shift_time ELSE 0 END) AS NHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.shift_type = 'work' THEN rcd.shift_time ELSE 0 END) AS NWorkHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.shift_type = 'eqmob' THEN rcd.shift_time ELSE 0 END) AS NEqmobHours, SUM(CASE WHEN rcd.shift_ampm = 'night' AND rcd.sh
ift_type = 'eqdemob' THEN rcd.shift_time ELSE 0 END) AS NEqdemobHours FROM OPENQUERY([LFMANAGE], 'SELECT p.job_no AS project, p.start_date, p.end_date, rs.roster_id, IFNULL(rs.role_id, 0) AS role1_id, IFNULL(r.role2_id, 0) AS role2_id, IFNULL(r.role3_id, 0) AS role3_id, rl.category AS role_category, rl.title AS role_title, rl.role_code AS role_code, rs.shift_date, rs.shift_ampm, rs.shift_time, rs.shift_type, s.client_id FROM lfmanage.t_roster_shift rs JOIN lfmanage.t_project AS p ON p.project_id = rs.project_id LEFT JOIN lfmanage.t_site AS s ON s.site_id = p.site_id JOIN lfmanage.t_roster AS r ON r.roster_id = rs.roster_id JOIN lfmanage.t_role AS rl ON rl.role_id = rs.role_id WHERE p.job_no = ''700704'' AND CASE WHEN ISNULL(rs.deleted) THEN 0 ELSE rs.deleted END = 0') AS rcd LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role2_id, role3_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_r
ole_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id')) AS rb_test1 ON rb_test1.client_id = rcd.client_id AND rb_test1.role1_id = rcd.role1_id AND rb_test1.role2_id = rcd.role2_id AND rb_test1.role3_id = rcd.role3_id LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role2_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id '
)) AS rb_test2 ON rb_test2.client_id = rcd.client_id AND rb_test2.role1_id = rcd.role1_id AND rb_test2.role2_id = rcd.role2_id LEFT OUTER JOIN (SELECT client_id, band_role_id, title, CASE WHEN CHARINDEX(UPPER(title),'SUPER') > 0 THEN 'super' ELSE 'trade' END AS category, role1_id, role3_id FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role3_id ')) AS rb_test3 ON rb_test3.client_id = rcd.client_id AND rb_test3.role1_id = rcd.role1_id AND rb_test3.role3_id = rcd.role3_id WHERE rcd.shift_date > '2017-01-01' GROUP BY rcd.project, rcd.start_date, rcd.end_date, rcd.roster_id, rcd.role1_id, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.category WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.category WHEN rb_test3.role
1_id IS NOT NULL THEN rb_test3.category ELSE rcd.role_category END, CASE WHEN rb_test1.role1_id IS NOT NULL THEN rb_test1.title WHEN rb_test2.role1_id IS NOT NULL THEN rb_test2.title WHEN rb_test3.role1_id IS NOT NULL THEN rb_test3.title ELSE rcd.role_title END, CASE WHEN rb_test1.role1_id IS NOT NULL THEN CAST(rb_test1.band_role_id AS VARCHAR) WHEN rb_test2.role1_id IS NOT NULL THEN CAST(rb_test2.band_role_id AS VARCHAR) WHEN rb_test3.role1_id IS NOT NULL THEN CAST(rb_test3.band_role_id AS VARCHAR) ELSE rcd.role_code END, rcd.shift_date) AS psrc INNER JOIN (SELECT job_no AS project, Client AS customer, '3700002213' AS subcode FROM [dbo].[vw_PlanningSystem_Projects] WHERE job_no = '700704') AS pr_jcm ON pr_jcm.project = psrc.project) AS ips_rc LEFT OUTER JOIN (SELECT rates.Client, rates.SubCode, mapping.Category, mapping.Shift, mapping.IPS_Role_Code, rates.Pronto_Role_Code, rates.Pronto_Role_Code_Description, rates.Rate, rates.Pronto_Role_Code_Old, rates.Pronto_Role_Code_Description_Old FROM (SELECT UPPER(Ca
tegory) AS Category, 'Day Shifts' AS Shift, IPS_Role_Code, Day_Cost_Code As Pronto_Role_Code FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping] UNION ALL SELECT UPPER(Category) AS Category, 'Night Shifts' AS Shift, IPS_Role_Code, Night_Cost_Code As Pronto_Role_Code FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]) AS mapping INNER JOIN (SELECT Client, SubCode, CASE WHEN Shift = 'Day Shift' THEN 'Day Shifts' WHEN Shift = 'Night Shift' THEN 'Night Shifts' Else '' END AS Shift, Pronto_Role_Code, Pronto_Role_Code_Description, Rate, Pronto_Role_Code_Old, Pronto_Role_Code_Description_Old FROM [LFBudgetEstimate].[dbo].[LFBE_SubCodes_Rates]) AS rates ON rates.Shift = mapping.Shift AND rates.Pronto_Role_Code = mapping.Pronto_Role_Code) AS lfbe ON lfbe.Client = ips_rc.customer AND lfbe.SubCode = ips_rc.subCode AND lfbe.Shift = ips_rc.Shift AND lfbe.IPS_Role_Code = ips_rc.role_code ORDER BY ips_rc.project ASC, ips_rc.role_title ASC, rl.list_order
Thanks for your help
Even with the formatting, you've got a lot going on here... Stack Overflow veterans, I'm just starting to dip my toes in here, so if this isn't correct, give me some grace.
In your first OPENQUERY statement, I don't see rl.list_order as a field being returned. If that's a column you're trying to ORDER BY, I think you should be able to add rl.list_order to your SELECT list within that statement which you alias as rcd.
Since that's within a nested sub-query, you'll want to elevate it to each of the calling queries. I think it's something like this... Try it out and post back with any errors.
SELECT ips_rc.ListOrder
, ips_rc.project
, lfbe.Category
, ips_rc.roster_id
, ips_rc.role_category
, ips_rc.role_title AS [ROLE]
, ips_rc.role_code
, ips_rc.role_title + ' (' + ips_rc.role_code + ')' AS PS_Role
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code, '') = ''
THEN 'TO_BE_MAPPED'
ELSE ISNULL(lfbe.Pronto_Role_Code, '')
END AS Pronto_Role_Code
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Description, '') = ''
THEN ips_rc.role_title
ELSE ISNULL(lfbe.Pronto_Role_Code_Description, '')
END AS Pronto_Role_Code_Description
, ISNULL(lfbe.Rate, 0) AS Rate
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Old, '') = ''
THEN ips_rc.role_title
ELSE lfbe.Pronto_Role_Code_Old
END AS Pronto_Role_Code_Old
, CASE
WHEN ISNULL(lfbe.Pronto_Role_Code_Description_Old, '') = ''
THEN 'TO_BE_MAPPED'
ELSE lfbe.Pronto_Role_Code_Description_Old
END AS Pronto_Role_Code_Description_Old
, ips_rc.Shift
, ips_rc.UOM
, ips_rc.DATE
, ips_rc.DHours
, ips_rc.NHours
FROM (
SELECT psrc.ListOrder -- Added
, psrc.project
, pr_jcm.customer
, pr_jcm.subcode
, psrc.roster_id
, psrc.role_id
, psrc.role_category
, psrc.role_title
, psrc.role_code
, CASE
WHEN SUM(CASE
WHEN psrc.DATE BETWEEN psrc.start_date
AND psrc.end_date
THEN psrc.NWorkHours
ELSE 0
END) OVER (PARTITION BY psrc.project, psrc.roster_id) >= SUM(CASE
WHEN psrc.DATE BETWEEN psrc.start_date
AND psrc.end_date
THEN psrc.DWorkHours
ELSE 0
END) OVER (PARTITION BY psrc.project, psrc.roster_id)
THEN 'Night Shifts'
ELSE 'Day Shifts'
END AS Shift, 'HOURS' AS UOM, psrc.DATE, psrc.DHours, psrc.NHours
FROM (
SELECT rcd.list_order --Added
, rcd.project
, rcd.start_date
, rcd.end_date
, rcd.roster_id
, rcd.role1_id AS role_id
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.category
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.category
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.category
ELSE rcd.role_category
END AS role_category
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.title
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.title
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.title
ELSE rcd.role_title
END AS role_title
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN CAST(rb_test1.band_role_id AS VARCHAR)
WHEN rb_test2.role1_id IS NOT NULL
THEN CAST(rb_test2.band_role_id AS VARCHAR)
WHEN rb_test3.role1_id IS NOT NULL
THEN CAST(rb_test3.band_role_id AS VARCHAR)
ELSE rcd.role_code
END AS role_code, rcd.shift_date AS DATE
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
THEN rcd.shift_time
ELSE 0
END) AS DHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'work'
THEN rcd.shift_time
ELSE 0
END) AS DWorkHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'eqmob'
THEN rcd.shift_time
ELSE 0
END) AS DEqmobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'day'
AND rcd.shift_type = 'eqdemob'
THEN rcd.shift_time
ELSE 0
END) AS DEqdemobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
THEN rcd.shift_time
ELSE 0
END) AS NHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'work'
THEN rcd.shift_time
ELSE 0
END) AS NWorkHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'eqmob'
THEN rcd.shift_time
ELSE 0
END) AS NEqmobHours
, SUM(CASE
WHEN rcd.shift_ampm = 'night'
AND rcd.shift_type = 'eqdemob'
THEN rcd.shift_time
ELSE 0
END) AS NEqdemobHours
FROM OPENQUERY([LFMANAGE], 'SELECT p.job_no AS project, p.start_date, p.end_date, rs.roster_id, IFNULL(rs.role_id, 0) AS role1_id, IFNULL(r.role2_id, 0) AS role2_id, IFNULL(r.role3_id, 0) AS role3_id, rl,ListOrder, rl.category AS role_category, rl.title AS role_title, rl.role_code AS role_code, rs.shift_date, rs.shift_ampm, rs.shift_time, rs.shift_type, s.client_id FROM lfmanage.t_roster_shift rs JOIN lfmanage.t_project AS p ON p.project_id = rs.project_id LEFT JOIN lfmanage.t_site AS s ON s.site_id = p.site_id JOIN lfmanage.t_roster AS r ON r.roster_id = rs.roster_id JOIN lfmanage.t_role AS rl ON rl.role_id = rs.role_id WHERE p.job_no = ''700704'' AND CASE WHEN ISNULL(rs.deleted) THEN 0 ELSE rs.deleted END = 0') AS rcd --Added
LEFT JOIN (
SELECT client_id
, band_role_id
, title
, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category
, role1_id
, role2_id
, role3_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id, brs.role3_id')
) AS rb_test1
ON rb_test1.client_id = rcd.client_id
AND rb_test1.role1_id = rcd.role1_id
AND rb_test1.role2_id = rcd.role2_id
AND rb_test1.role3_id = rcd.role3_id
LEFT JOIN (
SELECT client_id, band_role_id, title, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category, role1_id, role2_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role2_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role2_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role2_id ')
) AS rb_test2
ON rb_test2.client_id = rcd.client_id
AND rb_test2.role1_id = rcd.role1_id
AND rb_test2.role2_id = rcd.role2_id
LEFT JOIN (
SELECT client_id, band_role_id, title, CASE
WHEN CHARINDEX(UPPER(title), 'SUPER') > 0
THEN 'super'
ELSE 'trade'
END AS category, role1_id, role3_id
FROM OPENQUERY([LFMANAGE], 'SELECT br.client_id, MIN(brs.band_role_id) AS band_role_id, br.title, brs.role1_id, brs.role3_id FROM t_band_role_set AS brs INNER JOIN t_band_role AS br ON br.band_role_id = brs.band_role_id WHERE IFNULL(brs.role1_id, 0) <> 0 AND IFNULL(brs.role3_id, 0) <> 0 GROUP BY br.client_id, br.title, brs.role1_id, brs.role3_id ')
) AS rb_test3
ON rb_test3.client_id = rcd.client_id
AND rb_test3.role1_id = rcd.role1_id
AND rb_test3.role3_id = rcd.role3_id
WHERE rcd.shift_date > '2017-01-01'
GROUP BY rcd.list_order --Added
, rcd.project
, rcd.start_date
, rcd.end_date
, rcd.roster_id
, rcd.role1_id
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.category
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.category
WHEN rb_test3.ROLE1_id IS NOT NULL
THEN rb_test3.category
ELSE rcd.role_category
END
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN rb_test1.title
WHEN rb_test2.role1_id IS NOT NULL
THEN rb_test2.title
WHEN rb_test3.role1_id IS NOT NULL
THEN rb_test3.title
ELSE rcd.role_title
END
, CASE
WHEN rb_test1.role1_id IS NOT NULL
THEN CAST(rb_test1.band_role_id AS VARCHAR)
WHEN rb_test2.role1_id IS NOT NULL
THEN CAST(rb_test2.band_role_id AS VARCHAR)
WHEN rb_test3.role1_id IS NOT NULL
THEN CAST(rb_test3.band_role_id AS VARCHAR)
ELSE rcd.role_code
END
, rcd.shift_date
) AS psrc
INNER JOIN (
SELECT job_no AS project
, Client AS customer
, '3700002213' AS subcode
FROM [dbo].[vw_PlanningSystem_Projects]
WHERE job_no = '700704'
) AS pr_jcm
ON pr_jcm.project = psrc.project
) AS ips_rc
LEFT JOIN (
SELECT rates.Client
, rates.SubCode
, mapping.Category
, mapping.Shift
, mapping.IPS_Role_Code
, rates.Pronto_Role_Code
, rates.Pronto_Role_Code_Description
, rates.Rate
, rates.Pronto_Role_Code_Old
, rates.Pronto_Role_Code_Description_Old
FROM (
SELECT UPPER(Category) AS Category
, 'Day Shifts' AS Shift
, IPS_Role_Code
, Day_Cost_Code AS Pronto_Role_Code
FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]
UNION ALL
SELECT UPPER(Category) AS Category
, 'Night Shifts' AS Shift
, IPS_Role_Code
, Night_Cost_Code AS Pronto_Role_Code
FROM [LFBudgetEstimate].[dbo].[LFBE_RoleCode_MasterMapping]
) AS mapping
INNER JOIN (
SELECT Client
, SubCode
, CASE
WHEN Shift = 'Day Shift'
THEN 'Day Shifts'
WHEN Shift = 'Night Shift'
THEN 'Night Shifts'
ELSE ''
END AS Shift
, Pronto_Role_Code
, Pronto_Role_Code_Description
, Rate
, Pronto_Role_Code_Old
, Pronto_Role_Code_Description_Old
FROM [LFBudgetEstimate].[dbo].[LFBE_SubCodes_Rates]
) AS rates
ON rates.Shift = mapping.Shift
AND rates.Pronto_Role_Code = mapping.Pronto_Role_Code
) AS lfbe
ON lfbe.Client = ips_rc.customer
AND lfbe.SubCode = ips_rc.subCode
AND lfbe.Shift = ips_rc.Shift
AND lfbe.IPS_Role_Code = ips_rc.role_code
ORDER BY ips_rc.project ASC, ips_rc.role_title ASC, ips_rc.list_order ASC
You're right CSharp821 there's an awful lot going on there. I made the changes you suggested and it now works!
You are trying to access alias rl, however the rl alias is only visible within the OPENQUERY which has an alias of rcd. Try order by rcd.list_order instead of rl.list_order
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.