EF Core 3.1 OrderByDescending curious T-SQL translation - sql-server

I have the following Linq queries that differs only on the where clause:
Query 1:
var initialList = await
context.AlertDetailsDbSet
// Pouring the TrackedVehicule related graph
.Include(ad => ad.TrackedVehicule.Registration)
.Include(ad => ad.TrackedVehicule.Device)
.Include(ad => ad.TrackedVehicule.GpsBox.Icon)
.Include(ad => ad.TrackedVehicule.GpsBoxTypeNavigation.Icon)
.Include(ad => ad.TrackedVehicule.VehiculeGpsBoxInfo.VehiculeConfigurationNavigation)
// Loading the associated alert
.Include(ad => ad.Alert)
#if NETSTANDARD2_1
// This filter is not supported with EF Core 2.X
// It should be done client side
.Where(ad => ad.Alert.CompanyId == companyId && ad.Alert.AlertRule.Contains("SerializableContextAlert") && ad.AlertDateTime >= startDate && ad.AlertDateTime <= endDate && ad.TrackedVehicule != null && ad.TrackedVehicule.CompanyId == companyId && ad.TrackedVehicule.RowEnabled == true && (ad.TrackedVehicule.GpsBoxType == 29 || ad.TrackedVehicule.GpsBoxType == 12))
#endif
.Skip(0)
// A limit is applied on returned elements
.Take(1000)
.OrderByDescending(ad => ad.AlertDateTime)
// .Skip(skip)
// .Take(take)
// We disable the tracking mechanism because the context will be thrown away as soon as we have the data
.AsNoTracking()
// We want an asynchrounous execution
.ToListAsync(cancellationToken)
Query 2:
var initialList = await
context.AlertDetailsDbSet
// Pouring the TrackedVehicule related graph
.Include(ad => ad.TrackedVehicule.Registration)
.Include(ad => ad.TrackedVehicule.Device)
.Include(ad => ad.TrackedVehicule.GpsBox.Icon)
.Include(ad => ad.TrackedVehicule.GpsBoxTypeNavigation.Icon)
.Include(ad => ad.TrackedVehicule.VehiculeGpsBoxInfo.VehiculeConfigurationNavigation)
// Loading the associated alert
.Include(ad => ad.Alert)
#if NETSTANDARD2_1
// This filter is not supported with EF Core 2.X
// It should be done client side
.Where(ad => ad.Alert.CompanyId == companyId && ad.Alert.AlertRule.Contains("SerializableContextAlert") && ad.TrackedVehicule != null && ad.TrackedVehicule.RowEnabled == true && ad.TrackedVehicule.CompanyId == companyId && (ad.TrackedVehicule.GpsBoxType == 29 || ad.TrackedVehicule.GpsBoxType == 12) && ad.AckTime.HasValue == acknwoledged)
#endif
.OrderByDescending(ad => ad.AlertDateTime)
.Skip(skip)
.Take(take)
// We disable the tracking mechanism because the context will be thrown away as soon as we have the data
.AsNoTracking()
// We want an asynchrounous execution
.ToListAsync(cancellationToken)
Basically, the first query is (among aother things) filtering on a boolean property, while the second one is filtering on a range of dates.
My problem is that those queries are not translated to the same T-TSQL leading to different results.
TSQL 1 :
exec sp_executesql N'SELECT [t].[AlertDetailID], [t].[AckMachineName], [t].[AckPhoneNumber], [t].[AckTime], [t].[AckUserName], [t].[AlertDateTime], [t].[AlertID], [t].[AlertedCorridorId], [t].[AlertedItemId],
[t].[AssociatedVehiculeID], [t].[AssociatedVehiculeUserID], [t].[Context], [t].[CustomID], [t].[CustomInfo], [t].[DbInsertTime], [t].[IsFleetAlert], [t].[MessageStatus], [t].[ReceivedTime], [t].[RowVersion],
[t].[SafeProtectCustomInfo], [t].[TrackedVehiculeID], [t].[TrackedVehiculeUserID], [v0].[VehiculeID], [v0].[Address], [v0].[AddressProtocol], [v0].[BoardID], [v0].[Category], [v0].[CompanyID], [v0].[CustomId], [v0].[DbInsertTime], [v0].[Description], [v0].[GpsBoxSubType], [v0].[GpsBoxTrackingDelay], [v0].[GpsBoxType], [v0].[HardwareID], [v0].[HasGeoWorker], [v0].[IconID], [v0].[Name], [v0].[PhoneNumber], [v0].[RowEnabled], [v0].[RowVersion], [v0].[VehiculeUserID], [r].[VehiculeID], [r].[CompanyId], [r].[LatestRegistrationStatusChangeDate], [r].[RegistrationMailSent], [r].[RegistrationStatusId], [d].[VehiculeID], [d].[AppVersion], [d].[Brand], [d].[Details], [d].[Imei], [d].[Model], [d].[Name], [d].[OsVersion], [d].[RowVersion], [g].[GpsBoxTypeID], [g].[GpsBoxSubTypeID], [g].[IconId], [g].[Name], [i].[IconId], [i].[Category], [i].[FileName], [i].[Icon], [g0].[GpsBoxTypeId], [g0].[Category], [g0].[IconId], [g0].[Name], [i0].[IconId], [i0].[Category], [i0].[FileName], [i0].[Icon], [v1].[VehiculeID], [v1].[BoardConfiguration], [v1].[BoardConnected], [v1].[BoardCurrentAddress], [v1].[BoardLastCommunicationTime], [v1].[Connected], [v1].[CurrentAddress], [v1].[CurrentDelay], [v1].[FuelConsumptionEstimationTime], [v1].[HeartBeatPeriod], [v1].[InsureCoherence], [v1].[KillHedgehog], [v1].[LastCommunicationTime], [v1].[LastConnexionTime], [v1].[LastParkMileage], [v1].[LastParkMileageTime], [v1].[NormalTrackingMode], [v1].[SmartModeDelay], [v1].[SmartModeDistance], [v1].[TimeModeDelay], [v1].[UpdateStartTime], [v1].[UpdateStatus], [v1].[VehiculeConfiguration], [g1].[ConfigurationID], [g1].[ConfigName], [g1].[Firmware], [g1].[GpsBoxType], [g1].[Master], [g1].[MasterName], [g1].[SimContract], [g1].[System], [a1].[AlertID], [a1].[AlertEnabled], [a1].[AlertRule], [a1].[Always], [a1].[CalendarID], [a1].[Category], [a1].[CompanyID], [a1].[Description], [a1].[DisplayName], [a1].[RowEnabled], [a1].[RowVersion], [a1].[Shared], [a1].[UserID]
FROM (
SELECT [a].[AlertDetailID], [a].[AckMachineName], [a].[AckPhoneNumber], [a].[AckTime], [a].[AckUserName], [a].[AlertDateTime], [a].[AlertID], [a].[AlertedCorridorId], [a].[AlertedItemId], [a].[AssociatedVehiculeID], [a].[AssociatedVehiculeUserID], [a].[Context], [a].[CustomID], [a].[CustomInfo], [a].[DbInsertTime], [a].[IsFleetAlert], [a].[MessageStatus], [a].[ReceivedTime], [a].[RowVersion], [a].[SafeProtectCustomInfo], [a].[TrackedVehiculeID], [a].[TrackedVehiculeUserID], [a0].[AlertID] AS [AlertID0]
FROM [AlertDetail] AS [a]
INNER JOIN [Alert] AS [a0] ON [a].[AlertID] = [a0].[AlertID]
LEFT JOIN [Vehicule] AS [v] ON [a].[TrackedVehiculeID] = [v].[VehiculeID]
WHERE (((((([a0].[CompanyID] = #__companyId_0) AND (CHARINDEX(N''SerializableContextAlert'', [a0].[AlertRule]) > 0)) AND [v].[VehiculeID] IS NOT NULL) AND ([v].[RowEnabled] = CAST(1 AS bit))) AND ([v].[CompanyID] = #__companyId_0)) AND (([v].[GpsBoxType] = 29) OR ([v].[GpsBoxType] = 12))) AND (CASE
WHEN [a].[AckTime] IS NOT NULL THEN CAST(1 AS bit)
ELSE CAST(0 AS bit)
END = #__acknwoledged_1)
ORDER BY [a].[AlertDateTime] DESC
OFFSET #__p_2 ROWS FETCH NEXT #__p_3 ROWS ONLY
) AS [t]
LEFT JOIN [Vehicule] AS [v0] ON [t].[TrackedVehiculeID] = [v0].[VehiculeID]
LEFT JOIN [SafeProtect].[Registration] AS [r] ON [v0].[VehiculeID] = [r].[VehiculeID]
LEFT JOIN [SafeProtect].[Device] AS [d] ON [v0].[VehiculeID] = [d].[VehiculeID]
LEFT JOIN [GpsBoxSubType] AS [g] ON ([v0].[GpsBoxType] = [g].[GpsBoxTypeID]) AND ([v0].[GpsBoxSubType] = [g].[GpsBoxSubTypeID])
LEFT JOIN [cst].[Icon] AS [i] ON [g].[IconId] = [i].[IconId]
LEFT JOIN [GpsBoxType] AS [g0] ON [v0].[GpsBoxType] = [g0].[GpsBoxTypeId]
LEFT JOIN [cst].[Icon] AS [i0] ON [g0].[IconId] = [i0].[IconId]
LEFT JOIN [VehiculeGpsBoxInfo] AS [v1] ON [v0].[VehiculeID] = [v1].[VehiculeID]
LEFT JOIN [GpsBoxConfiguration] AS [g1] ON [v1].[VehiculeConfiguration] = [g1].[ConfigurationID]
INNER JOIN [Alert] AS [a1] ON [t].[AlertID] = [a1].[AlertID]
ORDER BY [t].[AlertDateTime] DESC',N'#__companyId_0 int,#__acknwoledged_1 bit,#__p_2 int,#__p_3 int',#__companyId_0=1013,#__acknwoledged_1=0,#__p_2=0,#__p_3=999
TSQL 2:
exec sp_executesql N'SELECT [t].[AlertDetailID], [t].[AckMachineName], [t].[AckPhoneNumber], [t].[AckTime], [t].[AckUserName], [t].[AlertDateTime], [t].[AlertID], [t].[AlertedCorridorId], [t].[AlertedItemId],
[t].[AssociatedVehiculeID], [t].[AssociatedVehiculeUserID], [t].[Context], [t].[CustomID], [t].[CustomInfo], [t].[DbInsertTime], [t].[IsFleetAlert], [t].[MessageStatus], [t].[ReceivedTime], [t].[RowVersion],
[t].[SafeProtectCustomInfo], [t].[TrackedVehiculeID], [t].[TrackedVehiculeUserID], [v0].[VehiculeID], [v0].[Address], [v0].[AddressProtocol], [v0].[BoardID], [v0].[Category], [v0].[CompanyID], [v0].[CustomId], [v0].[DbInsertTime], [v0].[Description], [v0].[GpsBoxSubType], [v0].[GpsBoxTrackingDelay], [v0].[GpsBoxType], [v0].[HardwareID], [v0].[HasGeoWorker], [v0].[IconID], [v0].[Name], [v0].[PhoneNumber], [v0].[RowEnabled], [v0].[RowVersion], [v0].[VehiculeUserID], [r].[VehiculeID], [r].[CompanyId], [r].[LatestRegistrationStatusChangeDate], [r].[RegistrationMailSent], [r].[RegistrationStatusId], [d].[VehiculeID], [d].[AppVersion], [d].[Brand], [d].[Details], [d].[Imei], [d].[Model], [d].[Name], [d].[OsVersion], [d].[RowVersion], [g].[GpsBoxTypeID], [g].[GpsBoxSubTypeID], [g].[IconId], [g].[Name], [i].[IconId], [i].[Category], [i].[FileName], [i].[Icon], [g0].[GpsBoxTypeId], [g0].[Category], [g0].[IconId], [g0].[Name], [i0].[IconId], [i0].[Category], [i0].[FileName], [i0].[Icon], [v1].[VehiculeID], [v1].[BoardConfiguration], [v1].[BoardConnected], [v1].[BoardCurrentAddress], [v1].[BoardLastCommunicationTime], [v1].[Connected], [v1].[CurrentAddress], [v1].[CurrentDelay], [v1].[FuelConsumptionEstimationTime], [v1].[HeartBeatPeriod], [v1].[InsureCoherence], [v1].[KillHedgehog], [v1].[LastCommunicationTime], [v1].[LastConnexionTime], [v1].[LastParkMileage], [v1].[LastParkMileageTime], [v1].[NormalTrackingMode], [v1].[SmartModeDelay], [v1].[SmartModeDistance], [v1].[TimeModeDelay], [v1].[UpdateStartTime], [v1].[UpdateStatus], [v1].[VehiculeConfiguration], [g1].[ConfigurationID], [g1].[ConfigName], [g1].[Firmware], [g1].[GpsBoxType], [g1].[Master], [g1].[MasterName], [g1].[SimContract], [g1].[System], [a1].[AlertID], [a1].[AlertEnabled], [a1].[AlertRule], [a1].[Always], [a1].[CalendarID], [a1].[Category], [a1].[CompanyID], [a1].[Description], [a1].[DisplayName], [a1].[RowEnabled], [a1].[RowVersion], [a1].[Shared], [a1].[UserID]
FROM (
SELECT [a].[AlertDetailID], [a].[AckMachineName], [a].[AckPhoneNumber], [a].[AckTime], [a].[AckUserName], [a].[AlertDateTime], [a].[AlertID], [a].[AlertedCorridorId], [a].[AlertedItemId], [a].[AssociatedVehiculeID], [a].[AssociatedVehiculeUserID], [a].[Context], [a].[CustomID], [a].[CustomInfo], [a].[DbInsertTime], [a].[IsFleetAlert], [a].[MessageStatus], [a].[ReceivedTime], [a].[RowVersion], [a].[SafeProtectCustomInfo], [a].[TrackedVehiculeID], [a].[TrackedVehiculeUserID], [a0].[AlertID] AS [AlertID0]
FROM [AlertDetail] AS [a]
INNER JOIN [Alert] AS [a0] ON [a].[AlertID] = [a0].[AlertID]
LEFT JOIN [Vehicule] AS [v] ON [a].[TrackedVehiculeID] = [v].[VehiculeID]
WHERE ((((((([a0].[CompanyID] = #__companyId_0) AND (CHARINDEX(N''SerializableContextAlert'', [a0].[AlertRule]) > 0)) AND ([a].[AlertDateTime] >= #__startDate_1)) AND ([a].[AlertDateTime] <= #__endDate_2)) AND [v].[VehiculeID] IS NOT NULL) AND ([v].[CompanyID] = #__companyId_0)) AND ([v].[RowEnabled] = CAST(1 AS bit))) AND (([v].[GpsBoxType] = 29) OR ([v].[GpsBoxType] = 12))
ORDER BY (SELECT 1)
OFFSET #__p_3 ROWS FETCH NEXT #__p_4 ROWS ONLY
) AS [t]
LEFT JOIN [Vehicule] AS [v0] ON [t].[TrackedVehiculeID] = [v0].[VehiculeID]
LEFT JOIN [SafeProtect].[Registration] AS [r] ON [v0].[VehiculeID] = [r].[VehiculeID]
LEFT JOIN [SafeProtect].[Device] AS [d] ON [v0].[VehiculeID] = [d].[VehiculeID]
LEFT JOIN [GpsBoxSubType] AS [g] ON ([v0].[GpsBoxType] = [g].[GpsBoxTypeID]) AND ([v0].[GpsBoxSubType] = [g].[GpsBoxSubTypeID])
LEFT JOIN [cst].[Icon] AS [i] ON [g].[IconId] = [i].[IconId]
LEFT JOIN [GpsBoxType] AS [g0] ON [v0].[GpsBoxType] = [g0].[GpsBoxTypeId]
LEFT JOIN [cst].[Icon] AS [i0] ON [g0].[IconId] = [i0].[IconId]
LEFT JOIN [VehiculeGpsBoxInfo] AS [v1] ON [v0].[VehiculeID] = [v1].[VehiculeID]
LEFT JOIN [GpsBoxConfiguration] AS [g1] ON [v1].[VehiculeConfiguration] = [g1].[ConfigurationID]
INNER JOIN [Alert] AS [a1] ON [t].[AlertID] = [a1].[AlertID]
ORDER BY [t].[AlertDateTime] DESC',N'#__companyId_0 int,#__startDate_1 datetime,#__endDate_2 datetime,#__p_3 int,#__p_4 int',#__companyId_0=1013,#__startDate_1='2020-09-07 21:59:59',#__endDate_2='2020-09-08 21:59:59',#__p_3=0,#__p_4=999
It took me some time to spot a tiny by impacting difference between the two queries.
If you look carefully, the first subquery contains an ORDER BY which is what I want:
ORDER BY [a].[AlertDateTime] DESC
The second linq query, despite using the same OderBy is translated to a TSQL subquery that contains
ORDER BY (SELECT 1)
That sounds crasy to me.
I hope that someone could explain what is going on.

It has nothing to do with filtering (Where), but the order of ordering (OrderBy{Descending}) and row limiting (Skip / Take) operators in LINQ query.
The fake ORDER BY (SELECT 1) definitely is generated for the LINQ query having the following fragment
.Skip(0)
.Take(1000)
.OrderByDescending(ad => ad.AlertDateTime)
// .Skip(skip)
// .Take(take)
As you can see, here the row limiting operators are applied before the ordering. Since SqlServer OFFSET FETCH SQL construct requires ORDER BY, EF Core translator inserts fake one (it would have been better to throw exception or let the database do that, but that's another story. Actually before EF Core 3.0 there was CoreEventId.RowLimitingOperationWithoutOrderByWarning which could be configured to throw, but for some unknown reason it has been obsoleted and has no effect in EF Core 3.x).
The correct place of row limiting of course is after ordering, as it is in the commented out code. So simply remove the (temporary I guess) Skip(0).Take(1000) and uncomment the .Skip(skip).Take(take). Problem solved.

Related

IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed

I am trying to identify Global Feature Relationships with SHAP values. The SHAP library returns three matrices and I am trying to select the SHAP matrix however, I am getting this error: "IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed".
The code I have is below:
df_score = spark.sql("select * from sandbox.yt_trng_churn_device")
#XGBoost Model
import pickle
from xgboost import XGBClassifier
from mlflow.tracking import MlflowClient
client = MlflowClient()
local_dir = "/dbfs/FileStore/"
local_path = client.download_artifacts
model_path = '/dbfs/FileStore/'
model = XGBClassifier()
model = pickle.load(open(model_path, 'rb'))
HorizonDate = datetime.datetime(2022, 9, 5)
df = df_score
score_data = df.toPandas()
results = model.predict_proba(score_data)
results_l = model.predict(score_data)
score_data["p"]=pd.Series( (v[1] for v in results) )
score_data["l"]=pd.Series( (v for v in results_l) )
spark.createDataFrame(score_data).createOrReplaceTempView("yt_vw_tmp_dev__scores")
spark.sql("create or replace table sandbox.yt_vw_tmp_dev__scores as select * from yt_vw_tmp_dev__scores")
#SHAP Analysis on XGBoost
from shap import KernelExplainer, summary_plot
sql = """
select d_a.*
from
hive_metastore.sandbox.yt_trng_device d_a
right join
(select decile, msisdn, MSISDN_L2L
from(
select ntile(10) over (order by p desc) as decile, msisdn, MSISDN_L2L
from sandbox.yt_vw_tmp_dev__scores
) inc
order by decile) d_b
on d_a.MSISDN_L2L = d_b.MSISDN_L2L and d_a.msisdn = d_b.msisdn
"""
df = spark.sql(sql).drop('msisdn', 'imei', 'imsi', 'event_date', 'MSISDN_L2L', 'account_id')
score_df = df.toPandas()
mode = score_df.mode().iloc[0]
sample = score_df.sample(n=min(100, score_df.shape[0]), random_state=508502835).fillna(mode)
predict = lambda x: model.predict(pd.DataFrame(x, columns=score_df.columns))
explainer = KernelExplainer(predict, sample, link="identity")
shap_values = explainer.shap_values(sample, l1_reg=False)
# The return of the explainer has three matrices, we will get the shap values one
shap_values = shap_values[ :, :, 0]
I am fairly new to coding but it would be great if someone could give some direction on this

Stored Procedure Executed in ADF Pipeline - Perfomance Issues

I am going to post this question divided in sections. Your help would be much appreciated!
Overview of the Issue
I have an issue with data refresh. Right now, I have a pipeline running on Azure Data Factory which is composed of 7 blocks. Each block hosts a stored procedure coded in SQL. Each block generates a table used by the next block. Tables average 3GB in weight. Each block takes between one and five hours to execute.
What I did so far
Given that I am pretty new to this world, I tried to abide by best practices. For example, each statement begins with SET NOCOUNT ON. I always specified column names in select statement, avoiding code blocks like SELECT * FROM TABLE. Also, each table has well defined Primary Keys (defined in the same order for each table) and, being SQL server, they also act as clustered indexes. As for the exemple reported below, these are two screenshots of the indexes:
and
I tried to exploit the MERGE statement. An example of one stored procedure is reported below. Note that I took the max() of all dimension fields because I joined sales and stock together at the level of Week, Product, Season, and Store and then grouped only by Week, Product, and Season. Hence, if I had stores that had a product but did not sale it I would have doubled the rows on NULL attributes.
CREATE PROCEDURE dbo.SP_W_LINE_LEVEL_RT_WORLD2
AS
SET NOCOUNT ON;
MERGE [dbo].[W_LINE_LEVEL_RT_WORLD2] AS TARGET
USING
(
SELECT
COALESCE(sales.FISCAL_YEARWEEK_NM, stock.FISCAL_YEARWEEK_NM) AS FISCAL_YEARWEEK_NM,
COALESCE(sales.BTN, stock.BTN_CD) AS BTN,
COALESCE(sales.ARTICLE_SEASON_DS, stock.ARTICLE_SEASON_DS) AS ARTICLE_SEASON_DS,
MAX(PRODUCT_IMAGE) AS PRODUCT_IMAGE,
--MAX(SUBCHANNEL) AS SUBCHANNEL,
MAX(GENDER) AS GENDER,
MAX(PRODUCT_CATEGORY) AS PRODUCT_CATEGORY,
MAX(FIRST_SEASON) AS FIRST_SEASON,
MAX(LAST_SEASON) AS LAST_SEASON,
MAX(TREND_DS) AS TREND_DS,
MAX(TREND_CD) AS TREND_CD,
MAX(COLOR) AS COLOR,
MAX(MATERIAL) AS MATERIAL,
MAX(FINISH) AS FINISH,
MAX(DEPARTMENT) AS DEPARTMENT,
MAX(PRODUCT_SUBCATEGORY) AS PRODUCT_SUBCATEGORY,
MAX(THEME_DS) AS THEME_DS,
MAX(THEME_FIX) AS THEME_FIX,
MAX(PRODUCT_SUBGROUP_DS) AS PRODUCT_SUBGROUP_DS,
MAX(PRODUCT_GROUP_DS) AS PRODUCT_GROUP_DS,
MAX(MODEL_DS) AS MODEL_DS,
MAX(PRODUCT_FAMILY_DS) AS PRODUCT_FAMILY_DS,
MAX(LAST_YEAR_WEEK_ABILITAZIONE) AS LAST_YEAR_WEEK_ABILITAZIONE,
-- AVERAGE LIFE TO DATE METRICS
MAX(FULL_PRICE_SALES_LTD) / NULLIF(MAX(TOTAL_QTY_LTD),0) AS AVERAGE_FULL_PRICE_CHF,
MAX(NET_REVENUES_LTD) / NULLIF(MAX(TOTAL_QTY_LTD),0) AS AVERAGE_SELLING_PRICE_CHF,
MAX(SALES_VALUE_STD_LTD) / NULLIF(MAX(TOTAL_QTY_LTD),0) AS STANDARD_COST_CHF,
MAX(SALES_VALUE_STD_LTD) / NULLIF(MAX(NET_REVENUES_LTD),0) AS MARGIN,
-- WEEK BY WEEK ANALYSIS
MAX(LAST_YEAR_MOTNH_ABILITAZIONE) AS LAST_YEAR_MOTNH_ABILITAZIONE,
SUM(NET_REVENUES) AS NET_REVENUES,
SUM(NET_SALES) AS NET_SALES,
SUM(FULL_PRICE_SALES) AS FULL_PRICE_SALES,
SUM(VAL_STDCOST) AS VAL_STDCOST,
SUM(TOT_PROMOTION) AS TOT_PROMOTION,
SUM(NET_SALES_MARKDOWN) AS NET_SALES_MARKDOWN,
SUM(NET_REVENUES_MARKDOWN) AS NET_REVENUES_MARKDOWN,
SUM(TOT_DISCOUNT) AS TOT_DISCOUNT,
SUM(SALES_QTY) AS SALES_QTY,
COUNT(DISTINCT STORE_SELLING) AS STORE_SELLING,
COUNT(DISTINCT COALESCE(sales.CLIENT_CD, stock.CLIENT_CD)) AS TOTAL_STORES_LW,
-- LIFE TO DATE ANALYSIS
MAX(NET_SALES_LTD) AS NET_SALES_LTD,
MAX(NET_REVENUES_LTD) AS NET_REVENUES_LTD,
MAX(FULL_PRICE_SALES_LTD) AS FULL_PRICE_SALES_LTD,
MAX(SALES_VALUE_STD_LTD) AS SALES_VALUE_STD_LTD,
MAX(FULL_PRICE_QTY_LTD) AS FULL_PRICE_QTY_LTD,
MAX(TOTAL_QTY_LTD) AS TOTAL_QTY_LTD,
MAX(NET_SALES_LTD_REGION) AS NET_SALES_LTD_REGION,
MAX(NET_REVENUES_LTD_REGION) AS NET_REVENUES_LTD_REGION,
MAX(FULL_PRICE_SALES_LTD_REGION) AS FULL_PRICE_SALES_LTD_REGION,
MAX(SALES_VALUE_STD_LTD_REGION) AS SALES_VALUE_STD_LTD_REGION,
MAX(FULL_PRICE_QTY_LTD_REGION) AS FULL_PRICE_QTY_LTD_REGION,
MAX(TOTAL_QTY_LTD_REGION) AS TOTAL_QTY_LTD_REGION,
COALESCE(MAX(WEEKS_ON_FLOOR_SEASONAL_AW_LTD),0) + COALESCE(MAX(WEEKS_ON_FLOOR_CARRY_AW_LTD),0) + COALESCE(MAX(WEEKS_ON_FLOOR_SEASONAL_SS_LTD),0) + COALESCE(MAX(WEEKS_ON_FLOOR_CARRY_SS_LTD),0) AS WEEKS_ON_FLOOR_LTD,
COALESCE(MAX(WEEKS_ON_FLOOR_SEASONAL_AW_LTD_REGION),0) + COALESCE(MAX(WEEKS_ON_FLOOR_CARRY_AW_LTD_REGION),0) + COALESCE(MAX(WEEKS_ON_FLOOR_SEASONAL_SS_LTD_REGION),0) + COALESCE(MAX(WEEKS_ON_FLOOR_CARRY_SS_LTD_REGION),0) AS WEEKS_ON_FLOOR_LTD_REGION,
COALESCE(MAX(RUNNING_STORE_SELLING_AW_CARRY_LTD),0) + COALESCE(MAX(RUNNING_STORE_SELLING_AW_SEASONAL_LTD),0) + COALESCE(MAX(RUNNING_STORE_SELLING_SS_CARRY_LTD),0) + COALESCE(MAX(RUNNING_STORE_SELLING_SS_SEASONAL_LTD),0) AS STORES_SELLING_LTD,
COALESCE(MAX(RUNNING_STORE_SELLING_AW_CARRY_LTD_REGION),0) + COALESCE(MAX(RUNNING_STORE_SELLING_AW_SEASONAL_LTD_REGION),0) + COALESCE(MAX(RUNNING_STORE_SELLING_SS_CARRY_LTD_REGION),0) + COALESCE(MAX(RUNNING_STORE_SELLING_SS_SEASONAL_LTD_REGION),0) AS STORES_SELLING_LTD_REGION,
-- STOCK DATA
COUNT(DISTINCT stock.CLIENT_CD) AS STOCK_STORES,
SUM(STOCK_QTY_NM) AS STOCK_QTY_NM,
SUM(STOCK_IN_STORE) AS STOCK_IN_STORE,
SUM(STOCK_IN_TRANSIT_TO_STORE) AS STOCK_IN_TRANSIT_TO_STORE,
SUM(STOCK_IN_REGIONAL_DC) AS STOCK_IN_REGIONAL_DC,
SUM(STOCK_IN_STORE) + SUM(STOCK_IN_TRANSIT_TO_STORE) + SUM(STOCK_IN_TRANSIT_TO_STORE) + SUM(STOCK_IN_REGIONAL_DC) AS TOTAL_STOCK_ON_HAND,
SUM(STOCK_ALLOCATED_IN_CENTRAL_WH) AS STOCK_ALLOCATED_IN_CENTRAL_WH,
SUM(STOCK_IN_TRANSIT_TO_REGION) AS STOCK_IN_TRANSIT_TO_REGION,
SUM(STOCK_FREE_CENTRAL_WH) AS STOCK_FREE_CENTRAL_WH
FROM
W_SALES_LINE_LEVEL_RT_WORLD2 sales
FULL OUTER JOIN
W_STOCK_LINE_LEVEL_RT_WORLD stock
ON
sales.FISCAL_YEARWEEK_NM = stock.FISCAL_YEARWEEK_NM
AND sales.BTN = stock.BTN_CD
AND sales.ARTICLE_SEASON_DS = stock.ARTICLE_SEASON_DS
AND sales.CLIENT_CD = stock.CLIENT_CD
GROUP BY
COALESCE(sales.FISCAL_YEARWEEK_NM, stock.FISCAL_YEARWEEK_NM),
COALESCE(sales.BTN, stock.BTN_CD),
COALESCE(sales.ARTICLE_SEASON_DS, stock.ARTICLE_SEASON_DS)
) NUOVA
ON
TARGET.FISCAL_YEARWEEK_NM = NUOVA.FISCAL_YEARWEEK_NM
AND TARGET.BTN = NUOVA.BTN
AND TARGET.ARTICLE_SEASON_DS = NUOVA.ARTICLE_SEASON_DS
WHEN MATCHED
THEN UPDATE SET
TARGET.FISCAL_YEARWEEK_NM = NUOVA.FISCAL_YEARWEEK_NM,
TARGET.BTN = NUOVA.BTN,
TARGET.ARTICLE_SEASON_DS = NUOVA.ARTICLE_SEASON_DS,
TARGET.PRODUCT_IMAGE = NUOVA.PRODUCT_IMAGE,
--TARGET.SUBCHANNEL = NUOVA.SUBCHANNEL,
TARGET.GENDER = NUOVA.GENDER,
TARGET.PRODUCT_CATEGORY = NUOVA.PRODUCT_CATEGORY,
TARGET.FIRST_SEASON = NUOVA.FIRST_SEASON,
TARGET.LAST_SEASON = NUOVA.LAST_SEASON,
TARGET.TREND_DS = NUOVA.TREND_DS,
TARGET.TREND_CD = NUOVA.TREND_CD,
TARGET.COLOR = NUOVA.COLOR,
TARGET.MATERIAL = NUOVA.MATERIAL,
TARGET.FINISH = NUOVA.FINISH,
TARGET.DEPARTMENT = NUOVA.DEPARTMENT,
TARGET.PRODUCT_SUBCATEGORY = NUOVA.PRODUCT_SUBCATEGORY,
TARGET.THEME_DS = NUOVA.THEME_DS,
TARGET.THEME_FIX = NUOVA.THEME_FIX,
TARGET.PRODUCT_SUBGROUP_DS = NUOVA.PRODUCT_SUBGROUP_DS,
TARGET.PRODUCT_GROUP_DS = NUOVA.PRODUCT_GROUP_DS,
TARGET.MODEL_DS = NUOVA.MODEL_DS,
TARGET.PRODUCT_FAMILY_DS = NUOVA.PRODUCT_FAMILY_DS,
TARGET.LAST_YEAR_WEEK_ABILITAZIONE = NUOVA.LAST_YEAR_WEEK_ABILITAZIONE,
TARGET.AVERAGE_FULL_PRICE_CHF = NUOVA.AVERAGE_FULL_PRICE_CHF,
TARGET.AVERAGE_SELLING_PRICE_CHF = NUOVA.AVERAGE_SELLING_PRICE_CHF,
TARGET.STANDARD_COST_CHF = NUOVA.STANDARD_COST_CHF,
TARGET.MARGIN = NUOVA.MARGIN,
TARGET.LAST_YEAR_MOTNH_ABILITAZIONE = NUOVA.LAST_YEAR_MOTNH_ABILITAZIONE,
TARGET.NET_REVENUES = NUOVA.NET_REVENUES,
TARGET.NET_SALES = NUOVA.NET_SALES,
TARGET.FULL_PRICE_SALES = NUOVA.FULL_PRICE_SALES,
TARGET.VAL_STDCOST = NUOVA.VAL_STDCOST,
TARGET.TOT_PROMOTION = NUOVA.TOT_PROMOTION,
TARGET.NET_SALES_MARKDOWN = NUOVA.NET_SALES_MARKDOWN,
TARGET.NET_REVENUES_MARKDOWN = NUOVA.NET_REVENUES_MARKDOWN,
TARGET.TOT_DISCOUNT = NUOVA.TOT_DISCOUNT,
TARGET.SALES_QTY = NUOVA.SALES_QTY,
TARGET.STORE_SELLING = NUOVA.STORE_SELLING,
TARGET.TOTAL_STORES_LW = NUOVA.TOTAL_STORES_LW,
TARGET.NET_SALES_LTD = NUOVA.NET_SALES_LTD,
TARGET.NET_REVENUES_LTD = NUOVA.NET_REVENUES_LTD,
TARGET.FULL_PRICE_SALES_LTD = NUOVA.FULL_PRICE_SALES_LTD,
TARGET.SALES_VALUE_STD_LTD = NUOVA.SALES_VALUE_STD_LTD,
TARGET.FULL_PRICE_QTY_LTD = NUOVA.FULL_PRICE_QTY_LTD,
TARGET.TOTAL_QTY_LTD = NUOVA.TOTAL_QTY_LTD,
TARGET.NET_SALES_LTD_REGION = NUOVA.NET_SALES_LTD_REGION,
TARGET.NET_REVENUES_LTD_REGION = NUOVA.NET_REVENUES_LTD_REGION,
TARGET.FULL_PRICE_SALES_LTD_REGION = NUOVA.FULL_PRICE_SALES_LTD_REGION,
TARGET.SALES_VALUE_STD_LTD_REGION = NUOVA.SALES_VALUE_STD_LTD_REGION,
TARGET.FULL_PRICE_QTY_LTD_REGION = NUOVA.FULL_PRICE_QTY_LTD_REGION,
TARGET.TOTAL_QTY_LTD_REGION = NUOVA.TOTAL_QTY_LTD_REGION,
TARGET.WEEKS_ON_FLOOR_LTD = NUOVA.WEEKS_ON_FLOOR_LTD,
TARGET.WEEKS_ON_FLOOR_LTD_REGION = NUOVA.WEEKS_ON_FLOOR_LTD_REGION,
TARGET.STORES_SELLING_LTD = NUOVA.STORES_SELLING_LTD,
TARGET.STORES_SELLING_LTD_REGION = NUOVA.STORES_SELLING_LTD_REGION,
TARGET.STOCK_STORES = NUOVA.STOCK_STORES,
TARGET.STOCK_QTY_NM = NUOVA.STOCK_QTY_NM,
TARGET.STOCK_IN_STORE = NUOVA.STOCK_IN_STORE,
TARGET.STOCK_IN_TRANSIT_TO_STORE = NUOVA.STOCK_IN_TRANSIT_TO_STORE,
TARGET.STOCK_IN_REGIONAL_DC = NUOVA.STOCK_IN_REGIONAL_DC,
TARGET.TOTAL_STOCK_ON_HAND = NUOVA.TOTAL_STOCK_ON_HAND,
TARGET.STOCK_ALLOCATED_IN_CENTRAL_WH = NUOVA.STOCK_ALLOCATED_IN_CENTRAL_WH,
TARGET.STOCK_IN_TRANSIT_TO_REGION = NUOVA.STOCK_IN_TRANSIT_TO_REGION,
TARGET.STOCK_FREE_CENTRAL_WH = NUOVA.STOCK_FREE_CENTRAL_WH
WHEN NOT MATCHED BY TARGET
THEN INSERT
(FISCAL_YEARWEEK_NM,
BTN,
ARTICLE_SEASON_DS,
PRODUCT_IMAGE,
--SUBCHANNEL,
GENDER,
PRODUCT_CATEGORY,
FIRST_SEASON,
LAST_SEASON,
TREND_DS,
TREND_CD,
COLOR,
MATERIAL,
FINISH,
DEPARTMENT,
PRODUCT_SUBCATEGORY,
THEME_DS,
THEME_FIX,
PRODUCT_SUBGROUP_DS,
PRODUCT_GROUP_DS,
MODEL_DS,
PRODUCT_FAMILY_DS,
LAST_YEAR_WEEK_ABILITAZIONE,
AVERAGE_FULL_PRICE_CHF,
AVERAGE_SELLING_PRICE_CHF,
STANDARD_COST_CHF,
MARGIN,
LAST_YEAR_MOTNH_ABILITAZIONE,
NET_REVENUES,
NET_SALES,
FULL_PRICE_SALES,
VAL_STDCOST,
TOT_PROMOTION,
NET_SALES_MARKDOWN,
NET_REVENUES_MARKDOWN,
TOT_DISCOUNT,
SALES_QTY,
STORE_SELLING,
TOTAL_STORES_LW,
NET_SALES_LTD,
NET_REVENUES_LTD,
FULL_PRICE_SALES_LTD,
SALES_VALUE_STD_LTD,
FULL_PRICE_QTY_LTD,
TOTAL_QTY_LTD,
NET_SALES_LTD_REGION,
NET_REVENUES_LTD_REGION,
FULL_PRICE_SALES_LTD_REGION,
SALES_VALUE_STD_LTD_REGION,
FULL_PRICE_QTY_LTD_REGION,
TOTAL_QTY_LTD_REGION,
WEEKS_ON_FLOOR_LTD,
WEEKS_ON_FLOOR_LTD_REGION,
STORES_SELLING_LTD,
STORES_SELLING_LTD_REGION,
STOCK_STORES,
STOCK_QTY_NM,
STOCK_IN_STORE,
STOCK_IN_TRANSIT_TO_STORE,
STOCK_IN_REGIONAL_DC,
TOTAL_STOCK_ON_HAND,
STOCK_ALLOCATED_IN_CENTRAL_WH,
STOCK_IN_TRANSIT_TO_REGION,
STOCK_FREE_CENTRAL_WH)
VALUES
(NUOVA.FISCAL_YEARWEEK_NM,
NUOVA.BTN,
NUOVA.ARTICLE_SEASON_DS,
NUOVA.PRODUCT_IMAGE,
--NUOVA.SUBCHANNEL,
NUOVA.GENDER,
NUOVA.PRODUCT_CATEGORY,
NUOVA.FIRST_SEASON,
NUOVA.LAST_SEASON,
NUOVA.TREND_DS,
NUOVA.TREND_CD,
NUOVA.COLOR,
NUOVA.MATERIAL,
NUOVA.FINISH,
NUOVA.DEPARTMENT,
NUOVA.PRODUCT_SUBCATEGORY,
NUOVA.THEME_DS,
NUOVA.THEME_FIX,
NUOVA.PRODUCT_SUBGROUP_DS,
NUOVA.PRODUCT_GROUP_DS,
NUOVA.MODEL_DS,
NUOVA.PRODUCT_FAMILY_DS,
NUOVA.LAST_YEAR_WEEK_ABILITAZIONE,
NUOVA.AVERAGE_FULL_PRICE_CHF,
NUOVA.AVERAGE_SELLING_PRICE_CHF,
NUOVA.STANDARD_COST_CHF,
NUOVA.MARGIN,
NUOVA.LAST_YEAR_MOTNH_ABILITAZIONE,
NUOVA.NET_REVENUES,
NUOVA.NET_SALES,
NUOVA.FULL_PRICE_SALES,
NUOVA.VAL_STDCOST,
NUOVA.TOT_PROMOTION,
NUOVA.NET_SALES_MARKDOWN,
NUOVA.NET_REVENUES_MARKDOWN,
NUOVA.TOT_DISCOUNT,
NUOVA.SALES_QTY,
NUOVA.STORE_SELLING,
NUOVA.TOTAL_STORES_LW,
NUOVA.NET_SALES_LTD,
NUOVA.NET_REVENUES_LTD,
NUOVA.FULL_PRICE_SALES_LTD,
NUOVA.SALES_VALUE_STD_LTD,
NUOVA.FULL_PRICE_QTY_LTD,
NUOVA.TOTAL_QTY_LTD,
NUOVA.NET_SALES_LTD_REGION,
NUOVA.NET_REVENUES_LTD_REGION,
NUOVA.FULL_PRICE_SALES_LTD_REGION,
NUOVA.SALES_VALUE_STD_LTD_REGION,
NUOVA.FULL_PRICE_QTY_LTD_REGION,
NUOVA.TOTAL_QTY_LTD_REGION,
NUOVA.WEEKS_ON_FLOOR_LTD,
NUOVA.WEEKS_ON_FLOOR_LTD_REGION,
NUOVA.STORES_SELLING_LTD,
NUOVA.STORES_SELLING_LTD_REGION,
NUOVA.STOCK_STORES,
NUOVA.STOCK_QTY_NM,
NUOVA.STOCK_IN_STORE,
NUOVA.STOCK_IN_TRANSIT_TO_STORE,
NUOVA.STOCK_IN_REGIONAL_DC,
NUOVA.TOTAL_STOCK_ON_HAND,
NUOVA.STOCK_ALLOCATED_IN_CENTRAL_WH,
NUOVA.STOCK_IN_TRANSIT_TO_REGION,
NUOVA.STOCK_FREE_CENTRAL_WH)
WHEN NOT MATCHED BY SOURCE
THEN DELETE;
The Road Ahead
Now, the query reported above alone took five hours to complete. I am sure there are better ways out there to improve this terrible performance. I hope some of you will land a hand here.
If I can be clearer on something, just drop a comment!
Thanks!

Optimize My Sql

I have a query in Epicor that I built using the BAQ Designer (which is just a gui for creating a SQL query). I recently made a change to add more data and now receive the following error.
The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query.
I'm sure the monster I created is not optimal and I could probably make some changes to make it better. If any of the experts could take a look and help it would be greatly appreciated as I am not a SQL expert, just good enough to break stuff.The SQL is:
With [Sales_Base] AS
(select
[SalesRep].[SalesRepCode] as [SalesRep_SalesRepCode],
[SalesRep].[Name] as [SalesRep_Name],
[InvcHead].[InvoiceNum] as [InvcHead_InvoiceNum],
[InvcHead].[InvoiceDate] as [InvcHead_InvoiceDate],
[InvcHead].[PONum] as [InvcHead_PONum],
[InvcDtl].[ExtPrice] as [InvcDtl_ExtPrice],
[Customer].[CustID] as [Customer_CustID],
[Customer].[Name] as [Customer_Name],
[SalesCat].[Description] as [SalesCat_Description],
[InvcDtl].[ProdCode] as [InvcDtl_ProdCode],
[SalesRep].[RoleCode] as [SalesRep_RoleCode],
[Customer].[GroupCode] as [Customer_GroupCode],
(Constants.Today) as [Calculated_Today],
(Constants.FirstDayOfMonth) as [Calculated_BOM],
(case
when DatePart(month,Constants.Today) in (1,4,7,10) then Constants.FirstDayOfMonth
when DatePart(month,Constants.Today) in (2,5,8,11) then DateAdd(month,-1,Constants.FirstDayOfMonth)
else DateAdd(month,-2,Constants.FirstDayOfMonth)
end) as [Calculated_BOQ],
(case
when DatePart(month,Constants.Today) = 1 then Constants.FirstDayOfMonth
when DatePart(month,Constants.Today) = 2 then DateAdd(month,-1,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 3 then DateAdd(month,-2,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 4 then DateAdd(month,-3,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 5 then DateAdd(month,-4,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 6 then DateAdd(month,-5,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 7 then DateAdd(month,-6,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 8 then DateAdd(month,-7,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 9 then DateAdd(month,-8,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 10 then DateAdd(month,-9,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 11 then DateAdd(month,-10,Constants.FirstDayOfMonth)
else DateAdd(month,-11,Constants.FirstDayOfMonth)
end) as [Calculated_BOY],
[Customer5].[CustID] as [Customer5_CustID],
[Customer5].[Name] as [Customer5_Name],
[Customer5].[GroupCode] as [Customer5_GroupCode],
[SalesRep].[EMailAddress] as [SalesRep_EMailAddress],
[InvcDtl].[InvoiceLine] as [InvcDtl_InvoiceLine],
(InvcDtl.ExtPrice + IsNull(InvcMisc.MiscAmt,0)) as [Calculated_InvcDtl_ExtPrice]
from Erp.SalesRep as SalesRep
left outer join Erp.InvcHead as InvcHead on
SalesRep.Company = InvcHead.Company
And
SalesRep.SalesRepCode = [Ice].entry(1,SalesRepList,'~')
Or
SalesRep.SalesRepCode = [Ice].entry(2,SalesRepList,'~')
Or
SalesRep.SalesRepCode = [Ice].entry(3,SalesRepList,'~')
Or
SalesRep.SalesRepCode = [Ice].entry(4,SalesRepList,'~')
Or
SalesRep.SalesRepCode = [Ice].entry(5,SalesRepList,'~')
and ( InvcHead.Posted = TRUE and InvcHead.InvoiceType <> 'DEP' )
left outer join Erp.InvcDtl as InvcDtl on
InvcHead.Company = InvcDtl.Company
And
InvcHead.InvoiceNum = InvcDtl.InvoiceNum
left outer join Erp.Customer as Customer on
InvcHead.Company = Customer.Company
And
InvcHead.SoldToCustNum = Customer.CustNum
left outer join Erp.SalesCat as SalesCat on
InvcDtl.Company = SalesCat.Company
And
InvcDtl.SalesCatID = SalesCat.SalesCatID
left outer join Erp.Customer as Customer5 on
InvcDtl.Company = Customer5.Company
And
InvcDtl.BTCustNum = Customer5.CustNum
left outer join Erp.InvcMisc as InvcMisc on
InvcDtl.Company = InvcMisc.Company
And
InvcDtl.InvoiceNum = InvcMisc.InvoiceNum
And
InvcDtl.InvoiceLine = InvcMisc.InvoiceLine
and ( InvcMisc.MiscCode = 'exp' )
where (SalesRep.RoleCode in ('sales', 'salesden', 'salesflx', 'salesmed', 'salespm') and SalesRep.SalesRepCode <> 'default' and SalesRep.SalesRepCode <> 'national' and SalesRep.SalesRepCode <> 'house' and SalesRep.SalesRepCode <> 'flexi' and SalesRep.SalesRepCode <> 'prescale' and SalesRep.InActive = FALSE))
,[Sales_Base_Add_MR] AS
(select
(Sales_Base5.SalesRep_SalesRepCode) as [Calculated_A_SalesRepCode],
(Sales_Base5.SalesRep_Name) as [Calculated_A_SalesRepName],
(Sales_Base5.InvcHead_InvoiceNum) as [Calculated_A_InvoiceNum],
(Sales_Base5.InvcHead_InvoiceDate) as [Calculated_A_InvoiceDate],
(Sales_Base5.InvcHead_PONum) as [Calculated_A_PONum],
(Sales_Base5.Calculated_InvcDtl_ExtPrice) as [Calculated_A_ExtPrice],
(Sales_Base5.Customer_CustID) as [Calculated_A_CustID],
(Sales_Base5.Customer_Name) as [Calculated_A_Cust],
(Sales_Base5.SalesCat_Description) as [Calculated_A_SalesCat],
(Sales_Base5.InvcDtl_ProdCode) as [Calculated_A_ProdCode],
(Sales_Base5.SalesRep_RoleCode) as [Calculated_A_RoleCode],
(Sales_Base5.Customer_GroupCode) as [Calculated_A_GroupCode],
(Sales_Base5.Calculated_Today) as [Calculated_A_Today],
(Sales_Base5.Calculated_BOM) as [Calculated_A_BOM],
(Sales_Base5.Calculated_BOQ) as [Calculated_A_BOQ],
(Sales_Base5.Calculated_BOY) as [Calculated_A_BOY],
(Sales_Base5.Customer5_CustID) as [Calculated_A_BTCustID],
(Sales_Base5.Customer5_Name) as [Calculated_A_BTCust],
(Sales_Base5.Customer5_GroupCode) as [Calculated_A_BTGroupCode],
[SalesRep2].[SalesRepCode] as [SalesRep2_SalesRepCode],
[SalesRep2].[Name] as [SalesRep2_Name],
[SalesRep2].[RoleCode] as [SalesRep2_RoleCode],
(Sales_Base5.SalesRep_EMailAddress) as [Calculated_A_Email],
(Sales_Base5.InvcDtl_InvoiceLine) as [Calculated_A_Line]
from Sales_Base as Sales_Base5
left outer join Erp.InvcHead as InvcHead1 on
Sales_Base5.InvcHead_InvoiceNum = InvcHead1.InvoiceNum
left outer join Erp.SalesRep as SalesRep2 on
InvcHead1.Company = SalesRep2.Company
And
[Ice].entry(1,SalesRepList,'~') = SalesRep2.SalesRepCode
Or
[Ice].entry(2,SalesRepList,'~') = SalesRep2.SalesRepCode
Or
[Ice].entry(3,SalesRepList,'~') = SalesRep2.SalesRepCode
Or
[Ice].entry(4,SalesRepList,'~') = SalesRep2.SalesRepCode
Or
[Ice].entry(5,SalesRepList,'~') = SalesRep2.SalesRepCode
and ( SalesRep2.RoleCode = 'mfgrep' )
where (Sales_Base5.Calculated_InvcDtl_ExtPrice <> 0 and Sales_Base5.InvcDtl_ProdCode <> ''))
,[Total] AS
(select
[Sales_Base_Add_MR3].[Calculated_A_InvoiceNum] as [Calculated_A_InvoiceNum],
(sum( Sales_Base_Add_MR3.Calculated_A_ExtPrice )) as [Calculated_Invoice_Total]
from Sales_Base_Add_MR as Sales_Base_Add_MR3
group by [Sales_Base_Add_MR3].[Calculated_A_InvoiceNum])
,[Key1] AS
(select
(Sales_Base_Add_MR.Calculated_A_SalesRepName) as [Calculated_Key1_SR],
(Sales_Base_Add_MR.Calculated_A_SalesRepName + Sales_Base_Add_MR.SalesRep2_Name) as [Calculated_Key1_Key]
from Sales_Base_Add_MR as Sales_Base_Add_MR
where (Sales_Base_Add_MR.SalesRep2_RoleCode = 'mfgrep')
group by (Sales_Base_Add_MR.Calculated_A_SalesRepName) as [Calculated_Key1_SR],
(Sales_Base_Add_MR.Calculated_A_SalesRepName + Sales_Base_Add_MR.SalesRep2_Name) as [Calculated_Key1_Key])
,[Key2] AS
(select
(Sales_Base_Add_MR2.Calculated_A_SalesRepName) as [Calculated_Key2_SR],
(Sales_Base_Add_MR2.Calculated_A_SalesRepName + Sales_Base_Add_MR2.Calculated_A_BTCustID) as [Calculated_Key2_Key]
from Sales_Base_Add_MR as Sales_Base_Add_MR2
where (Sales_Base_Add_MR2.Calculated_A_BTGroupCode in ('dend', 'flxd', 'medd', 'prsd'))
group by (Sales_Base_Add_MR2.Calculated_A_SalesRepName) as [Calculated_Key2_SR],
(Sales_Base_Add_MR2.Calculated_A_SalesRepName + Sales_Base_Add_MR2.Calculated_A_BTCustID) as [Calculated_Key2_Key])
,[B] AS
(select
(Sales_Base_Add_MR14.Calculated_A_SalesRepCode) as [Calculated_B_SalesRepCode],
(Sales_Base_Add_MR14.Calculated_A_SalesRepName) as [Calculated_B_SalesRepName],
(Sales_Base_Add_MR14.Calculated_A_InvoiceNum) as [Calculated_B_InvoiceNum],
(Sales_Base_Add_MR14.Calculated_A_InvoiceDate) as [Calculated_B_InvoiceDate],
(Sales_Base_Add_MR14.Calculated_A_PONum) as [Calculated_B_PONum],
(Total.Calculated_Invoice_Total) as [Calculated_B_OrderTotal],
(Sales_Base_Add_MR14.Calculated_A_CustID) as [Calculated_B_CustID],
(Sales_Base_Add_MR14.Calculated_A_Cust) as [Calculated_B_Cust],
(Sales_Base_Add_MR14.Calculated_A_RoleCode) as [Calculated_B_RoleCode],
(Sales_Base_Add_MR14.Calculated_A_GroupCode) as [Calculated_B_GroupCode],
(Sales_Base_Add_MR14.Calculated_A_Today) as [Calculated_B_Today],
(Sales_Base_Add_MR14.Calculated_A_BOM) as [Calculated_B_BOM],
(Sales_Base_Add_MR14.Calculated_A_BOQ) as [Calculated_B_BOQ],
(Sales_Base_Add_MR14.Calculated_A_BOY) as [Calculated_B_BOY],
(Sales_Base_Add_MR14.Calculated_A_BTCustID) as [Calculated_B_BTCustID],
(Sales_Base_Add_MR14.Calculated_A_BTCust) as [Calculated_B_BTCust],
(Sales_Base_Add_MR14.Calculated_A_BTGroupCode) as [Calculated_B_BTGroupCode],
(Sales_Base_Add_MR14.SalesRep2_SalesRepCode) as [Calculated_B_MRCode],
(Sales_Base_Add_MR14.SalesRep2_Name) as [Calculated_B_MRName],
(Sales_Base_Add_MR14.SalesRep2_RoleCode) as [Calculated_B_MRRoleCode],
(Sales_Base_Add_MR14.Calculated_A_Email) as [Calculated_B_Email],
(Key1.Calculated_Key1_Key) as [Calculated_B_Key],
(Key2.Calculated_Key2_Key) as [Calculated_B_Key2]
from Sales_Base_Add_MR as Sales_Base_Add_MR14
left outer join Key1 as Key1 on
Sales_Base_Add_MR14.Calculated_A_SalesRepName = Key1.Calculated_Key1_SR
And
Calculated_A_SalesRepName + SalesRep2_Name = Key1.Calculated_Key1_Key
left outer join Key2 as Key2 on
Sales_Base_Add_MR14.Calculated_A_SalesRepName = Key2.Calculated_Key2_SR
And
Calculated_A_SalesRepName + Calculated_A_BTCustID = Key2.Calculated_Key2_Key
left outer join Total as Total on
Sales_Base_Add_MR14.Calculated_A_InvoiceNum = Total.Calculated_A_InvoiceNum
group by (Sales_Base_Add_MR14.Calculated_A_SalesRepCode) as [Calculated_B_SalesRepCode],
(Sales_Base_Add_MR14.Calculated_A_SalesRepName) as [Calculated_B_SalesRepName],
(Sales_Base_Add_MR14.Calculated_A_InvoiceNum) as [Calculated_B_InvoiceNum],
(Sales_Base_Add_MR14.Calculated_A_InvoiceDate) as [Calculated_B_InvoiceDate],
(Sales_Base_Add_MR14.Calculated_A_PONum) as [Calculated_B_PONum],
(Total.Calculated_Invoice_Total) as [Calculated_B_OrderTotal],
(Sales_Base_Add_MR14.Calculated_A_CustID) as [Calculated_B_CustID],
(Sales_Base_Add_MR14.Calculated_A_Cust) as [Calculated_B_Cust],
(Sales_Base_Add_MR14.Calculated_A_RoleCode) as [Calculated_B_RoleCode],
(Sales_Base_Add_MR14.Calculated_A_GroupCode) as [Calculated_B_GroupCode],
(Sales_Base_Add_MR14.Calculated_A_Today) as [Calculated_B_Today],
(Sales_Base_Add_MR14.Calculated_A_BOM) as [Calculated_B_BOM],
(Sales_Base_Add_MR14.Calculated_A_BOQ) as [Calculated_B_BOQ],
(Sales_Base_Add_MR14.Calculated_A_BOY) as [Calculated_B_BOY],
(Sales_Base_Add_MR14.Calculated_A_BTCustID) as [Calculated_B_BTCustID],
(Sales_Base_Add_MR14.Calculated_A_BTCust) as [Calculated_B_BTCust],
(Sales_Base_Add_MR14.Calculated_A_BTGroupCode) as [Calculated_B_BTGroupCode],
(Sales_Base_Add_MR14.SalesRep2_SalesRepCode) as [Calculated_B_MRCode],
(Sales_Base_Add_MR14.SalesRep2_Name) as [Calculated_B_MRName],
(Sales_Base_Add_MR14.SalesRep2_RoleCode) as [Calculated_B_MRRoleCode],
(Sales_Base_Add_MR14.Calculated_A_Email) as [Calculated_B_Email],
(Key1.Calculated_Key1_Key) as [Calculated_B_Key],
(Key2.Calculated_Key2_Key) as [Calculated_B_Key2])
,[Sales_BOM] AS
(select
(B1.Calculated_B_SalesRepName) as [Calculated_Sales_BOM_Rep],
(sum( B1.Calculated_B_OrderTotal )) as [Calculated_Sales_BOM_Sum]
from B as B1
where (B1.Calculated_B_InvoiceDate >= B1.Calculated_B_BOM and B1.Calculated_B_InvoiceDate <= B1.Calculated_B_Today)
group by (B1.Calculated_B_SalesRepName) as [Calculated_Sales_BOM_Rep])
,[Sales_BOQ] AS
(select
(B2.Calculated_B_SalesRepName) as [Calculated_Sales_BOQ_Rep],
(sum( B2.Calculated_B_OrderTotal )) as [Calculated_Sales_BOQ_Sum]
from B as B2
where (B2.Calculated_B_InvoiceDate >= B2.Calculated_B_BOQ and B2.Calculated_B_InvoiceDate <= B2.Calculated_B_Today)
group by (B2.Calculated_B_SalesRepName) as [Calculated_Sales_BOQ_Rep])
,[Sales_BOY] AS
(select
(B3.Calculated_B_SalesRepName) as [Calculated_Sales_BOY_Rep],
(sum( B3.Calculated_B_OrderTotal )) as [Calculated_Sales_BOY_Sum]
from B as B3
where (B3.Calculated_B_InvoiceDate >= B3.Calculated_B_BOY and B3.Calculated_B_InvoiceDate <= B3.Calculated_B_Today)
group by (B3.Calculated_B_SalesRepName) as [Calculated_Sales_BOY_Rep])
,[MR_BOM] AS
(select
(sum( B5.Calculated_B_OrderTotal )) as [Calculated_MR_BOM_Sum],
(B5.Calculated_B_Key) as [Calculated_MR_BOM_Key]
from B as B5
where (B5.Calculated_B_InvoiceDate >= B5.Calculated_B_BOM and B5.Calculated_B_InvoiceDate <= B5.Calculated_B_Today and B5.Calculated_B_MRRoleCode = 'mfgrep')
group by (B5.Calculated_B_Key) as [Calculated_MR_BOM_Key])
,[MR_BOQ] AS
(select
(sum( B6.Calculated_B_OrderTotal )) as [Calculated_MR_BOQ_Sum],
(B6.Calculated_B_Key) as [Calculated_MR_BOQ_Key]
from B as B6
where (B6.Calculated_B_InvoiceDate >= B6.Calculated_B_BOQ and B6.Calculated_B_InvoiceDate <= B6.Calculated_B_Today and B6.Calculated_B_MRRoleCode = 'mfgrep')
group by (B6.Calculated_B_Key) as [Calculated_MR_BOQ_Key])
,[MR_BOY] AS
(select
(sum( B7.Calculated_B_OrderTotal )) as [Calculated_MR_BOY_Sum],
(B7.Calculated_B_Key) as [Calculated_MR_BOY_Key],
(B7.Calculated_B_MRName) as [Calculated_MR_BOY_MR]
from B as B7
where (B7.Calculated_B_InvoiceDate >= B7.Calculated_B_BOY and B7.Calculated_B_InvoiceDate <= B7.Calculated_B_Today and B7.Calculated_B_MRRoleCode = 'mfgrep')
group by (B7.Calculated_B_Key) as [Calculated_MR_BOY_Key],
(B7.Calculated_B_MRName) as [Calculated_MR_BOY_MR])
,[Dist_BOM] AS
(select
(sum( B9.Calculated_B_OrderTotal )) as [Calculated_Dist_BOM_Sum],
(B9.Calculated_B_Key2) as [Calculated_Dist_BOM_Key]
from B as B9
where (B9.Calculated_B_InvoiceDate >= B9.Calculated_B_BOM and B9.Calculated_B_InvoiceDate <= B9.Calculated_B_Today and B9.Calculated_B_BTGroupCode in ('dend', 'flxd', 'medd', 'prsd'))
group by (B9.Calculated_B_Key2) as [Calculated_Dist_BOM_Key])
,[Dist_BOQ] AS
(select
(sum( B10.Calculated_B_OrderTotal )) as [Calculated_Dist_BOQ_Sum],
(B10.Calculated_B_Key2) as [Calculated_Dist_BOQ_Key]
from B as B10
where (B10.Calculated_B_InvoiceDate >= B10.Calculated_B_BOQ and B10.Calculated_B_InvoiceDate <= B10.Calculated_B_Today and B10.Calculated_B_BTGroupCode in ('dend', 'flxd', 'medd', 'prsd'))
group by (B10.Calculated_B_Key2) as [Calculated_Dist_BOQ_Key])
,[Dist_BOY] AS
(select
(sum( B11.Calculated_B_OrderTotal )) as [Calculated_Dist_BOY_Sum],
(B11.Calculated_B_Key2) as [Calculated_Dist_BOY_Key],
(B11.Calculated_B_BTCustID) as [Calculated_Dist_BOY_ID],
(B11.Calculated_B_BTCust) as [Calculated_Dist_BOYDist],
(B11.Calculated_B_BTGroupCode) as [Calculated_Dist_BOY_Group]
from B as B11
where (B11.Calculated_B_InvoiceDate >= B11.Calculated_B_BOY and B11.Calculated_B_InvoiceDate <= B11.Calculated_B_Today and B11.Calculated_B_BTGroupCode in ('dend', 'flxd', 'medd', 'prsd'))
group by (B11.Calculated_B_Key2) as [Calculated_Dist_BOY_Key],
(B11.Calculated_B_BTCustID) as [Calculated_Dist_BOY_ID],
(B11.Calculated_B_BTCust) as [Calculated_Dist_BOYDist],
(B11.Calculated_B_BTGroupCode) as [Calculated_Dist_BOY_Group])
,[Sales_Group] AS
(select
(B12.Calculated_B_SalesRepName) as [Calculated_Sales_Group_SR],
(B12.Calculated_B_Email) as [Calculated_Sales_Group_Email]
from B as B12
group by (B12.Calculated_B_SalesRepName) as [Calculated_Sales_Group_SR],
(B12.Calculated_B_Email) as [Calculated_Sales_Group_Email])
,[MR_Group] AS
(select
(B13.Calculated_B_SalesRepName) as [Calculated_MR_Group_SR],
(B13.Calculated_B_Email) as [Calculated_MR_Group_Email],
(B13.Calculated_B_Key) as [Calculated_MR_Group_Key]
from B as B13
where (B13.Calculated_B_Key is not null)
group by (B13.Calculated_B_SalesRepName) as [Calculated_MR_Group_SR],
(B13.Calculated_B_Email) as [Calculated_MR_Group_Email],
(B13.Calculated_B_Key) as [Calculated_MR_Group_Key])
,[Dist_Group] AS
(select
(B15.Calculated_B_SalesRepName) as [Calculated_Dist_Group_SR],
(B15.Calculated_B_Email) as [Calculated_Dist_Group_Email],
(B15.Calculated_B_Key2) as [Calculated_Dist_Group_Key]
from B as B15
where (B15.Calculated_B_Key2 is not null)
group by (B15.Calculated_B_SalesRepName) as [Calculated_Dist_Group_SR],
(B15.Calculated_B_Email) as [Calculated_Dist_Group_Email],
(B15.Calculated_B_Key2) as [Calculated_Dist_Group_Key])
,[Report] AS
(select
(IsNull(B16.Calculated_B_SalesRepCode,'Sales')) as [Calculated_R_SalesRepCode],
(Sales_Group.Calculated_Sales_Group_SR) as [Calculated_R_SalesRepName],
(IsNull(B16.Calculated_B_InvoiceNum,9999999)) as [Calculated_R_InvoiceNum],
(IsNull(B16.Calculated_B_InvoiceDate, convert(date, '30991231', 112))) as [Calculated_R_InvoiceDate],
(B16.Calculated_B_PONum) as [Calculated_R_PONum],
(B16.Calculated_B_OrderTotal) as [Calculated_R_InvoiceTotal],
(B16.Calculated_B_CustID) as [Calculated_R_CustID],
(B16.Calculated_B_Cust) as [Calculated_R_Cust],
(B16.Calculated_B_RoleCode) as [Calculated_R_RoleCode],
(B16.Calculated_B_GroupCode) as [Calculated_R_GroupCode],
(B16.Calculated_B_BTCustID) as [Calculated_R_BTCustID],
(B16.Calculated_B_BTCust) as [Calculated_R_BTCust],
(B16.Calculated_B_BTGroupCode) as [Calculated_R_BTGroupCode],
(B16.Calculated_B_MRCode) as [Calculated_R_MRCode],
(B16.Calculated_B_MRName) as [Calculated_R_MRName],
(B16.Calculated_B_MRRoleCode) as [Calculated_R_MRRoleCode],
(Sales_Group.Calculated_Sales_Group_Email) as [Calculated_R_Email],
(B16.Calculated_B_Key) as [Calculated_R_Key],
(B16.Calculated_B_Key2) as [Calculated_R_Key2],
(Sales_BOM.Calculated_Sales_BOM_Sum) as [Calculated_R_SalesBOM],
(Sales_BOQ.Calculated_Sales_BOQ_Sum) as [Calculated_R_SalesBOQ],
(Sales_BOY.Calculated_Sales_BOY_Sum) as [Calculated_R_SalesBOY],
(NULL) as [Calculated_R_MRBOM],
(NULL) as [Calculated_R_MRBOQ],
(NULL) as [Calculated_R_MRBOY],
(NULL) as [Calculated_R_DistBOM],
(NULL) as [Calculated_R_DistBOQ],
(NULL) as [Calculated_R_DistBOY]
from Sales_Group as Sales_Group
left outer join B as B16 on
Sales_Group.Calculated_Sales_Group_SR = B16.Calculated_B_SalesRepName
and ( B16.Calculated_B_Key is null and B16.Calculated_B_Key2 is null and B16.Calculated_B_InvoiceDate >= B16.Calculated_B_BOM and B16.Calculated_B_InvoiceDate <= B16.Calculated_B_Today )
left outer join Sales_BOM as Sales_BOM on
Sales_Group.Calculated_Sales_Group_SR = Sales_BOM.Calculated_Sales_BOM_Rep
left outer join Sales_BOQ as Sales_BOQ on
Sales_Group.Calculated_Sales_Group_SR = Sales_BOQ.Calculated_Sales_BOQ_Rep
left outer join Sales_BOY as Sales_BOY on
Sales_Group.Calculated_Sales_Group_SR = Sales_BOY.Calculated_Sales_BOY_Rep
UNION
select
(B17.Calculated_B_SalesRepCode) as [Calculated_C_1],
(MR_Group.Calculated_MR_Group_SR) as [Calculated_C_2],
(B17.Calculated_B_InvoiceNum) as [Calculated_C_3],
(B17.Calculated_B_InvoiceDate) as [Calculated_C_4],
(B17.Calculated_B_PONum) as [Calculated_C_5],
(B17.Calculated_B_OrderTotal) as [Calculated_C_6],
(B17.Calculated_B_CustID) as [Calculated_C_9],
(B17.Calculated_B_Cust) as [Calculated_C_10],
(B17.Calculated_B_RoleCode) as [Calculated_C_13],
(B17.Calculated_B_GroupCode) as [Calculated_C_14],
(B17.Calculated_B_BTCustID) as [Calculated_C_15],
(B17.Calculated_B_BTCust) as [Calculated_C_16],
(B17.Calculated_B_BTGroupCode) as [Calculated_C_17],
(B17.Calculated_B_MRCode) as [Calculated_C_20],
(IsNull(B17.Calculated_B_MRName,MR_BOY.Calculated_MR_BOY_MR)) as [Calculated_C_21],
(B17.Calculated_B_MRRoleCode) as [Calculated_C_22],
(MR_Group.Calculated_MR_Group_Email) as [Calculated_C_23],
(MR_Group.Calculated_MR_Group_Key) as [Calculated_C_24],
(B17.Calculated_B_Key2) as [Calculated_C_25],
(Sales_BOM2.Calculated_Sales_BOM_Sum) as [Calculated_C_27],
(Sales_BOQ2.Calculated_Sales_BOQ_Sum) as [Calculated_C_28],
(Sales_BOY2.Calculated_Sales_BOY_Sum) as [Calculated_C_29],
(MR_BOM.Calculated_MR_BOM_Sum) as [Calculated_C_31],
(MR_BOQ.Calculated_MR_BOQ_Sum) as [Calculated_C_32],
(MR_BOY.Calculated_MR_BOY_Sum) as [Calculated_C_33],
(NULL) as [Calculated_C_35],
(NULL) as [Calculated_C_36],
(NULL) as [Calculated_C_37]
from MR_Group as MR_Group
left outer join B as B17 on
MR_Group.Calculated_MR_Group_Key = B17.Calculated_B_Key
and ( B17.Calculated_B_InvoiceDate >= B17.Calculated_B_BOM and B17.Calculated_B_InvoiceDate <= B17.Calculated_B_Today )
left outer join MR_BOM as MR_BOM on
MR_Group.Calculated_MR_Group_Key = MR_BOM.Calculated_MR_BOM_Key
left outer join MR_BOQ as MR_BOQ on
MR_Group.Calculated_MR_Group_Key = MR_BOQ.Calculated_MR_BOQ_Key
left outer join MR_BOY as MR_BOY on
MR_Group.Calculated_MR_Group_Key = MR_BOY.Calculated_MR_BOY_Key
left outer join Sales_BOM as Sales_BOM2 on
MR_Group.Calculated_MR_Group_SR = Sales_BOM2.Calculated_Sales_BOM_Rep
left outer join Sales_BOQ as Sales_BOQ2 on
MR_Group.Calculated_MR_Group_SR = Sales_BOQ2.Calculated_Sales_BOQ_Rep
left outer join Sales_BOY as Sales_BOY2 on
MR_Group.Calculated_MR_Group_SR = Sales_BOY2.Calculated_Sales_BOY_Rep
UNION
select
(B18.Calculated_B_SalesRepCode) as [Calculated_D_1],
(Dist_Group.Calculated_Dist_Group_SR) as [Calculated_D_2],
(B18.Calculated_B_InvoiceNum) as [Calculated_D_3],
(B18.Calculated_B_InvoiceDate) as [Calculated_D_4],
(B18.Calculated_B_PONum) as [Calculated_D_5],
(B18.Calculated_B_OrderTotal) as [Calculated_D_6],
(B18.Calculated_B_CustID) as [Calculated_D_9],
(B18.Calculated_B_Cust) as [Calculated_D_10],
(B18.Calculated_B_RoleCode) as [Calculated_D_13],
(B18.Calculated_B_GroupCode) as [Calculated_D_14],
(IsNull(B18.Calculated_B_BTCustID,Dist_BOY.Calculated_Dist_BOY_ID)) as [Calculated_D_15],
(IsNull(B18.Calculated_B_BTCust,Dist_BOY.Calculated_Dist_BOYDist)) as [Calculated_D_16],
(IsNull(B18.Calculated_B_BTGroupCode,Dist_BOY.Calculated_Dist_BOY_Group)) as [Calculated_D_17],
(B18.Calculated_B_MRCode) as [Calculated_D_20],
(B18.Calculated_B_MRName) as [Calculated_D_21],
(B18.Calculated_B_MRRoleCode) as [Calculated_D_22],
(Dist_Group.Calculated_Dist_Group_Email) as [Calculated_D_23],
(B18.Calculated_B_Key) as [Calculated_D_24],
(Dist_Group.Calculated_Dist_Group_Key) as [Calculated_D_25],
(Sales_BOM1.Calculated_Sales_BOM_Sum) as [Calculated_D_27],
(Sales_BOQ1.Calculated_Sales_BOQ_Sum) as [Calculated_D_28],
(Sales_BOY1.Calculated_Sales_BOY_Sum) as [Calculated_D_29],
(NULL) as [Calculated_D_31],
(NULL) as [Calculated_D_32],
(NULL) as [Calculated_D_33],
(Dist_BOM.Calculated_Dist_BOM_Sum) as [Calculated_D_35],
(Dist_BOQ.Calculated_Dist_BOQ_Sum) as [Calculated_D_36],
(Dist_BOY.Calculated_Dist_BOY_Sum) as [Calculated_D_37]
from Dist_Group as Dist_Group
left outer join B as B18 on
Dist_Group.Calculated_Dist_Group_Key = B18.Calculated_B_Key2
and ( B18.Calculated_B_InvoiceDate >= B18.Calculated_B_BOM and B18.Calculated_B_InvoiceDate <= B18.Calculated_B_Today )
left outer join Dist_BOM as Dist_BOM on
Dist_Group.Calculated_Dist_Group_Key = Dist_BOM.Calculated_Dist_BOM_Key
left outer join Dist_BOQ as Dist_BOQ on
Dist_Group.Calculated_Dist_Group_Key = Dist_BOQ.Calculated_Dist_BOQ_Key
left outer join Dist_BOY as Dist_BOY on
Dist_Group.Calculated_Dist_Group_Key = Dist_BOY.Calculated_Dist_BOY_Key
left outer join Sales_BOM as Sales_BOM1 on
Dist_Group.Calculated_Dist_Group_SR = Sales_BOM1.Calculated_Sales_BOM_Rep
left outer join Sales_BOQ as Sales_BOQ1 on
Dist_Group.Calculated_Dist_Group_SR = Sales_BOQ1.Calculated_Sales_BOQ_Rep
left outer join Sales_BOY as Sales_BOY1 on
Dist_Group.Calculated_Dist_Group_SR = Sales_BOY1.Calculated_Sales_BOY_Rep)
select
[Report].[Calculated_R_SalesRepCode] as [Calculated_R_SalesRepCode],
[Report].[Calculated_R_SalesRepName] as [Calculated_R_SalesRepName],
[Report].[Calculated_R_InvoiceNum] as [Calculated_R_InvoiceNum],
[Report].[Calculated_R_InvoiceDate] as [Calculated_R_InvoiceDate],
[Report].[Calculated_R_PONum] as [Calculated_R_PONum],
[Report].[Calculated_R_InvoiceTotal] as [Calculated_R_InvoiceTotal],
[Report].[Calculated_R_CustID] as [Calculated_R_CustID],
[Report].[Calculated_R_Cust] as [Calculated_R_Cust],
[Report].[Calculated_R_RoleCode] as [Calculated_R_RoleCode],
[Report].[Calculated_R_GroupCode] as [Calculated_R_GroupCode],
[Report].[Calculated_R_BTCustID] as [Calculated_R_BTCustID],
[Report].[Calculated_R_BTCust] as [Calculated_R_BTCust],
[Report].[Calculated_R_BTGroupCode] as [Calculated_R_BTGroupCode],
[Report].[Calculated_R_MRCode] as [Calculated_R_MRCode],
[Report].[Calculated_R_MRName] as [Calculated_R_MRName],
[Report].[Calculated_R_MRRoleCode] as [Calculated_R_MRRoleCode],
[Report].[Calculated_R_Email] as [Calculated_R_Email],
[Report].[Calculated_R_Key] as [Calculated_R_Key],
[Report].[Calculated_R_Key2] as [Calculated_R_Key2],
[Report].[Calculated_R_SalesBOM] as [Calculated_R_SalesBOM],
[Report].[Calculated_R_SalesBOQ] as [Calculated_R_SalesBOQ],
[Report].[Calculated_R_SalesBOY] as [Calculated_R_SalesBOY],
[Report].[Calculated_R_MRBOM] as [Calculated_R_MRBOM],
[Report].[Calculated_R_MRBOQ] as [Calculated_R_MRBOQ],
[Report].[Calculated_R_MRBOY] as [Calculated_R_MRBOY],
[Report].[Calculated_R_DistBOM] as [Calculated_R_DistBOM],
[Report].[Calculated_R_DistBOQ] as [Calculated_R_DistBOQ],
[Report].[Calculated_R_DistBOY] as [Calculated_R_DistBOY]
from Report as Report
a) Look for simplifying parts of the query. For example, this part can be vastly simplified:
(case
when DatePart(month,Constants.Today) = 1 then Constants.FirstDayOfMonth
when DatePart(month,Constants.Today) = 2 then DateAdd(month,-1,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 3 then DateAdd(month,-2,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 4 then DateAdd(month,-3,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 5 then DateAdd(month,-4,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 6 then DateAdd(month,-5,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 7 then DateAdd(month,-6,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 8 then DateAdd(month,-7,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 9 then DateAdd(month,-8,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 10 then DateAdd(month,-9,Constants.FirstDayOfMonth)
when DatePart(month,Constants.Today) = 11 then DateAdd(month,-10,Constants.FirstDayOfMonth)
else DateAdd(month,-11,Constants.FirstDayOfMonth)
end) as [Calculated_BOY],
Could be instead
(case
when DatePart(month,Constants.Today) = 12 then Constants.FirstDayOfMonth
else DateAdd(month, - ( DatePart(month,Constants.Today) - 1), Constants.FirstDayOfMonth) end ) as [Calculated_BOY]
b) Separate the subselects into temporary tables, particularly those that you can verify produce relatively small resultsets (let's say thousand of rows or less). Providing those temporary tables to the select instead of subselects will help the query processor
I really wonder what is
[Ice].entry(1,SalesRepList,'~')
if it is a function, you can work on it.
But it seems to be creating constant values, not dynamic per row
I see that the query is formed of multiple CTE expressions
The Report CTE is formed of UNIONs can be converted to UNION ALLs if possible
And many GROUP By for calculations
Perhaps those can be converted to new aggregation syntax with SUM() function using PARTITION BY clause

I want to subtract Curr_YTD and Prev_YTD and divide it by Prev_YTD. The stored procedure needs correction

its a stored procedure taking the sum of columns now I want to take subtract the values Curr_YTD and Prev_YTD and divide by Prev_YTD.
The stored procedure needs correction.
Kindly let me know if anybody could help with subtract and divide operator.
SELECT B.TEAMNAME, B.PRIMARY_CODE, B.HIERARCHY_LEVEL, A.THERAPEUTICCLASS_CD,
B.PRODUCT_CODE, B.CHANNEL, B.UNIT,'P' PM_INDICATOR, A.PROCESSINGPERIOD_DT,
A.LOCATION_CODE, A.GEOGRAPHY_NAME,party_id, A.TRX_QTY1, A.TRX_QTY2, A.TRX_QTY3, A.TRX_QTY4,
A.TRX_QTY5,A.TRX_QTY6,A.TRX_QTY7,A.TRX_QTY8,A.TRX_QTY9,A.TRX_QTY10,A.TRX_QTY11,
A.TRX_QTY12,A.TRX_QTY13,A.TRX_QTY14,A.TRX_QTY15,A.TRX_QTY16,A.TRX_QTY17,A.TRX_QTY18,
A.TRX_QTY19,A.TRX_QTY20,A.TRX_QTY21, A.TRX_QTY22,A.TRX_QTY23,A.TRX_QTY24,
A.TRX_QTY1+ A.TRX_QTY2+ A.TRX_QTY3+ A.TRX_QTY4+A.TRX_QTY5+A.TRX_QTY6+A.TRX_QTY7+A.TRX_QTY8 Curr_YTD,
A.TRX_QTY13+A.TRX_QTY14+A.TRX_QTY15+A.TRX_QTY16+A.TRX_QTY17+A.TRX_QTY18+A.TRX_QTY19+A.TRX_QTY20 Prev_YTD,
(Curr_YTD Minus Prev_YTD)/Prev_YTD YTD
FROM (SELECT TTP.LILLY_MARKET_ID THERAPEUTICCLASS_CD,
TO_DATE(XPS.PROCESSINGPERIOD_DT, 'MM / DD / YYYY') PROCESSINGPERIOD_DT,
TTP.PRIMARY_CD PRIMARY_CODE,
TLP.LOCATION_CODE,
RTRIM(TLP.Geography_name) GEOGRAPHY_NAME,
ttp.party_id,
SUM(XPS.TRX_QTY1) TRX_QTY1,SUM(XPS.TRX_QTY2) TRX_QTY2,SUM(XPS.TRX_QTY3) TRX_QTY3,
SUM(XPS.TRX_QTY4) TRX_QTY4,SUM(XPS.TRX_QTY5) TRX_QTY5,SUM(XPS.TRX_QTY6) TRX_QTY6,
SUM(XPS.TRX_QTY7) TRX_QTY7,SUM(XPS.TRX_QTY8) TRX_QTY8,SUM(XPS.TRX_QTY9) TRX_QTY9,
SUM(XPS.TRX_QTY10) TRX_QTY10,SUM(XPS.TRX_QTY11) TRX_QTY11,SUM(XPS.TRX_QTY12) TRX_QTY12,
SUM(XPS.TRX_QTY13) TRX_QTY13,SUM(XPS.TRX_QTY14) TRX_QTY14,SUM(XPS.TRX_QTY15) TRX_QTY15,
SUM(XPS.TRX_QTY16) TRX_QTY16,SUM(XPS.TRX_QTY17) TRX_QTY17,SUM(XPS.TRX_QTY18) TRX_QTY18,
SUM(XPS.TRX_QTY19) TRX_QTY19,SUM(XPS.TRX_QTY20) TRX_QTY20,SUM(XPS.TRX_QTY21) TRX_QTY21,
SUM(XPS.TRX_QTY22) TRX_QTY22,SUM(XPS.TRX_QTY23) TRX_QTY23,SUM(XPS.TRX_QTY24) TRX_QTY24
FROM T_SALECRDTNG_XPS_48861 XPS,
T_SALECRDTNG_TTP_49354 TTP,
T_SALESCRD_LOCTNMAPNG TLP
WHERE TTP.PARTY_ID = XPS.PRFSNL_ID
AND TTP.LILLY_MARKET_ID = XPS.LLY_THERAPEUTICCLASS_CD
AND TLP.MAPPINGID = 48871
and TLP.PRIMARY_CODE = 'USUA'
AND XPS.PRODUCT_ID IN ('10210','10215')
AND XPS.LLY_PRODUCT_ID IN ('203825','208142')
AND TLP.LOCATION_CODE = TRIM(TTP.MASTER_GEO_ID)
AND TTP.PRIMARY_CD = TLP.PRIMARY_CODE
group by TTP.LILLY_MARKET_ID,
TTP.PRIMARY_CD,
TO_DATE(XPS.PROCESSINGPERIOD_DT, 'MM / DD / YYYY'),
TLP.LOCATION_CODE,
ttp.party_id,
TLP.Geography_name) A,
(SELECT DISTINCT UPPER(SC.TEAMNAME) TEAMNAME,
DECODE(SC.HIERARCHY_LEVEL, 'TERRITORY', 3, 'DISTRICT', 2, 'AREA', 1, 'REGION',
6,'DIVISION',0, NULL) HIERARCHY_LEVEL,
SC.PRODUCT_CODE PRODUCT_CODE,
SC.PRIMARY_CODE PRIMARY_CODE,
SC.CHANNEL CHANNEL,
SC.UNIT UNIT
FROM T_SALESCRDNG_CONFIG SC
WHERE SC.CONFIGID = 48994
AND SC.PRIMARY_CODE = 'USUA'
AND SC.PRODUCT_CODE = 'CIALIS TOTAL') B
WHERE A.PRIMARY_CODE = B.PRIMARY_CODE
;
Just add a SELCET and make your existing query a sub-query, something like this
SELECT rs.TEAMNAME, rs.PRIMARY_CODE, rs.HIERARCHY_LEVEL, rs.THERAPEUTICCLASS_CD,
rs.PRODUCT_CODE, rs.CHANNEL, rs.UNIT,rs.PM_INDICATOR, rs.PROCESSINGPERIOD_DT,
rs.LOCATION_CODE, rs.GEOGRAPHY_NAME,rs.party_id, rs.TRX_QTY1, rs.TRX_QTY2, rs.TRX_QTY3, rs.TRX_QTY4,
rs.TRX_QTY5,rs.TRX_QTY6,rs.TRX_QTY7,rs.TRX_QTY8,rs.TRX_QTY9,rs.TRX_QTY10,rs.TRX_QTY11,
rs.TRX_QTY12,rs.TRX_QTY13,rs.TRX_QTY14,rs.TRX_QTY15,rs.TRX_QTY16,rs.TRX_QTY17,rs.TRX_QTY18,
rs.TRX_QTY19,rs.TRX_QTY20,rs.TRX_QTY21, rs.TRX_QTY22,rs.TRX_QTY23,rs.TRX_QTY24,
rs.Curr_YTD, rs.Prev_YTD,
(rs.Curr_YTD - rs.Prev_YTD)/rs.Prev_YTD YTD
FROM
(
SELECT B.TEAMNAME, B.PRIMARY_CODE, B.HIERARCHY_LEVEL, A.THERAPEUTICCLASS_CD,
B.PRODUCT_CODE, B.CHANNEL, B.UNIT,'P' PM_INDICATOR, A.PROCESSINGPERIOD_DT,
A.LOCATION_CODE, A.GEOGRAPHY_NAME,party_id, A.TRX_QTY1, A.TRX_QTY2, A.TRX_QTY3, A.TRX_QTY4,
A.TRX_QTY5,A.TRX_QTY6,A.TRX_QTY7,A.TRX_QTY8,A.TRX_QTY9,A.TRX_QTY10,A.TRX_QTY11,
A.TRX_QTY12,A.TRX_QTY13,A.TRX_QTY14,A.TRX_QTY15,A.TRX_QTY16,A.TRX_QTY17,A.TRX_QTY18,
A.TRX_QTY19,A.TRX_QTY20,A.TRX_QTY21, A.TRX_QTY22,A.TRX_QTY23,A.TRX_QTY24,
A.TRX_QTY1+ A.TRX_QTY2+ A.TRX_QTY3+ A.TRX_QTY4+A.TRX_QTY5+A.TRX_QTY6+A.TRX_QTY7+A.TRX_QTY8 Curr_YTD,
A.TRX_QTY13+A.TRX_QTY14+A.TRX_QTY15+A.TRX_QTY16+A.TRX_QTY17+A.TRX_QTY18+A.TRX_QTY19+A.TRX_QTY20 Prev_YTD
FROM (SELECT TTP.LILLY_MARKET_ID THERAPEUTICCLASS_CD,
TO_DATE(XPS.PROCESSINGPERIOD_DT, 'MM / DD / YYYY') PROCESSINGPERIOD_DT,
TTP.PRIMARY_CD PRIMARY_CODE,
TLP.LOCATION_CODE,
RTRIM(TLP.Geography_name) GEOGRAPHY_NAME,
ttp.party_id,
SUM(XPS.TRX_QTY1) TRX_QTY1,SUM(XPS.TRX_QTY2) TRX_QTY2,SUM(XPS.TRX_QTY3) TRX_QTY3,
SUM(XPS.TRX_QTY4) TRX_QTY4,SUM(XPS.TRX_QTY5) TRX_QTY5,SUM(XPS.TRX_QTY6) TRX_QTY6,
SUM(XPS.TRX_QTY7) TRX_QTY7,SUM(XPS.TRX_QTY8) TRX_QTY8,SUM(XPS.TRX_QTY9) TRX_QTY9,
SUM(XPS.TRX_QTY10) TRX_QTY10,SUM(XPS.TRX_QTY11) TRX_QTY11,SUM(XPS.TRX_QTY12) TRX_QTY12,
SUM(XPS.TRX_QTY13) TRX_QTY13,SUM(XPS.TRX_QTY14) TRX_QTY14,SUM(XPS.TRX_QTY15) TRX_QTY15,
SUM(XPS.TRX_QTY16) TRX_QTY16,SUM(XPS.TRX_QTY17) TRX_QTY17,SUM(XPS.TRX_QTY18) TRX_QTY18,
SUM(XPS.TRX_QTY19) TRX_QTY19,SUM(XPS.TRX_QTY20) TRX_QTY20,SUM(XPS.TRX_QTY21) TRX_QTY21,
SUM(XPS.TRX_QTY22) TRX_QTY22,SUM(XPS.TRX_QTY23) TRX_QTY23,SUM(XPS.TRX_QTY24) TRX_QTY24
FROM T_SALECRDTNG_XPS_48861 XPS,
T_SALECRDTNG_TTP_49354 TTP,
T_SALESCRD_LOCTNMAPNG TLP
WHERE TTP.PARTY_ID = XPS.PRFSNL_ID
AND TTP.LILLY_MARKET_ID = XPS.LLY_THERAPEUTICCLASS_CD
AND TLP.MAPPINGID = 48871
and TLP.PRIMARY_CODE = 'USUA'
AND XPS.PRODUCT_ID IN ('10210','10215')
AND XPS.LLY_PRODUCT_ID IN ('203825','208142')
AND TLP.LOCATION_CODE = TRIM(TTP.MASTER_GEO_ID)
AND TTP.PRIMARY_CD = TLP.PRIMARY_CODE
group by TTP.LILLY_MARKET_ID,
TTP.PRIMARY_CD,
TO_DATE(XPS.PROCESSINGPERIOD_DT, 'MM / DD / YYYY'),
TLP.LOCATION_CODE,
ttp.party_id,
TLP.Geography_name) A,
(SELECT DISTINCT UPPER(SC.TEAMNAME) TEAMNAME,
DECODE(SC.HIERARCHY_LEVEL, 'TERRITORY', 3, 'DISTRICT', 2, 'AREA', 1, 'REGION',
6,'DIVISION',0, NULL) HIERARCHY_LEVEL,
SC.PRODUCT_CODE PRODUCT_CODE,
SC.PRIMARY_CODE PRIMARY_CODE,
SC.CHANNEL CHANNEL,
SC.UNIT UNIT
FROM T_SALESCRDNG_CONFIG SC
WHERE SC.CONFIGID = 48994
AND SC.PRIMARY_CODE = 'USUA'
AND SC.PRODUCT_CODE = 'CIALIS TOTAL') B
WHERE A.PRIMARY_CODE = B.PRIMARY_CODE
) rs
;

Select in LINQ with a strange value #p__linq__0

I have this select in LINQ
public List<EquipamentoNoDiscovery> GetEquipamentosNoDiscovery(int imID)
var lista = (from ma in ctx.macaddress
join m in ctx.mac on
ma.address_mac equals m.mac_id into g1
from m in g1.DefaultIfEmpty()
join ml in ctx.mac_link on
m.mac_id equals ml.mac_id into g2
from ml in g2.DefaultIfEmpty()
join im in ctx.immobile on
ml.link_id equals im.immobile_id into g3
from im in g3.DefaultIfEmpty()
join en in ctx.enterprise on
im.enterprise_id equals en.enterprise_id into g4
from en in g4.DefaultIfEmpty()
join pl in ctx.port_link on
ma.address_id equals pl.address_id into g5
from pl in g5.DefaultIfEmpty()
join p in ctx.port on
new { pl.sw_id, pl.port_id } equals new { p.sw_id, p.port_id }
join s in ctx.switch_lan on
pl.sw_id equals s.sw_id into g6
from s in g6.DefaultIfEmpty()
where pl.address_id == imID
select new
{
Regiao = en.enterprise_u_name,
Predio = im.immobile_u_name,
Equipamento = m.host,
TipoPlaca = m.mac_type,
Mac = ma.address_mac,
Ip_ma = ma.address_ip,
Ip_m = m.ip_address,
Comunidade = s.sw_community,
IpSwitch = s.sw_ip,
PortaIndex = p.port_index,
PortaNome = p.port_name
});
ObjectQuery oQuery = (ObjectQuery)lista;
string cmdSQL = oQuery.ToTraceString();
When I use the command oQuery.ToTraceString(), I can see this "where pl.address_id == imID" become this "WHERE [Extent6].[address_id] = #p_linq_0".
Then my select always return empty, if in SQL command I change the value #p_linq_0 to a number, It works fine.
Any suggestions, please?
Thanks!
That's just a query parameter which comes from this where claused.
where pl.address_id == imID
Your log should also show the value which has been passed for that parameter, which should be the value of imID. Check that value - it's possible that it's not what you expected it to be.

Resources