To ensure that you only retrieve items that exist in the ITScope_CompData_temp table (and not all rows from the stockinfo table), you need to adjust your query so that it filters out rows where there is no match between ITScope_CompData_temp and stockinfo. This can be achieved by reversing the join logic and ensuring that the stockinfo table is only queried for rows that have a corresponding match in the ITScope_CompData_temp table.
Key Changes
Use an INNER JOIN instead of a LEFT JOIN to ensure that only matching rows between ITScope_CompData_temp and stockinfo are included.
Add a filter to ensure that only items present in the ITScope_CompData_temp table are considered.
Here’s the revised query:
Revised Query
-- Step 1: Get latest extraction_date from ITScope
DECLARE @LatestDate CHAR(8) = (
SELECT TOP 1 extraction_date
FROM [Controlling].[dbo].[ITScope_CompData_temp]
WHERE ISDATE(LEFT(extraction_date, 4) + '-' + SUBSTRING(extraction_date, 5, 2) + '-' + RIGHT(extraction_date, 2)) = 1
ORDER BY extraction_date DESC
);
-- Step 2: Get latest DKK to EUR exchange rate from EET Germany table
DECLARE @DKK_to_EUR DECIMAL(18,6);
-- FIX: Use TRY_CAST to safely convert the rate before division, and filter out non-numeric rates.
SELECT TOP 1
@DKK_to_EUR = TRY_CAST([Relational Exch. Rate Amount] AS DECIMAL(20, 8)) / 100.0
FROM
[Financialsdk_BI].[dbo].[EET Germany$Currency Exchange Rate]
WHERE
[Currency Code] = 'DKK'
AND TRY_CAST([Relational Exch. Rate Amount] AS DECIMAL(20, 8)) IS NOT NULL
ORDER BY
[Starting Date] DESC;
-- Step 3: Join ITScope and Stockinfo with conditional matching based on batchname
SELECT
si.[No.] AS [ItemNo],
si.[Manufacturer Part No],
cd.[manufacturerSKU],
cd.[supplierSKU],
cd.[supplierName],
cd.[manufacturerName],
TRY_CAST(cd.[price] AS DECIMAL(18, 2)) AS [Competitor_Price_EUR],
TRY_CAST(cd.[stock] AS DECIMAL(18, 0)) AS [Competitor_Stock],
-- FIX: Ensure Cost Price is cast safely BEFORE multiplication
TRY_CAST(TRY_CAST(si.[Cost Price] AS DECIMAL(18, 6)) * @DKK_to_EUR AS DECIMAL(18, 4)) AS [CostPrice_EUR],
TRY_CAST(si.[Stock] AS DECIMAL(18, 0)) AS [EET_Stock],
cd.[extraction_date],
cd.[batchname]
INTO #ITSCOPE_Joined
FROM [Controlling].[dbo].[ITScope_CompData_temp] cd
-- Use INNER JOIN to ensure only matching rows are included
INNER JOIN [Controlling].[dbo].[stockinfo] si
ON (
(cd.batchname = 'C00' AND cd.supplierSKU = si.[Manufacturer Part No])
OR
(cd.batchname <> 'C00' AND cd.supplierSKU = si.[No.])
)
WHERE cd.extraction_date = @LatestDate
AND TRY_CAST(cd.[price] AS DECIMAL(18, 6)) IS NOT NULL
AND TRY_CAST(cd.[stock] AS DECIMAL(18, 6)) IS NOT NULL;
Explanation of Changes
INNER JOIN Instead of LEFT JOIN:
A LEFT JOIN includes all rows from the left table (ITScope_CompData_temp) even if there is no match in the right table (stockinfo). By switching to an INNER JOIN, we ensure that only rows with a match in both tables are included.
Filtering Based on ITScope_CompData_temp:
The WHERE clause ensures that only rows from ITScope_CompData_temp with a valid extraction_date (matching @LatestDate) and numeric values for [price] and [stock] are considered.
Performance Consideration:
Since the stockinfo table contains over a million rows, the INNER JOIN ensures that SQL Server only processes rows in stockinfo that have a corresponding match in ITScope_CompData_temp. This significantly reduces the number of rows processed and improves performance.
Additional Optimization Suggestions
If performance is still an issue due to the large size of the stockinfo table, consider the following optimizations:
Indexes:
Ensure that the columns used in the ON clause ([Manufacturer Part No] and [No.] in stockinfo, and [supplierSKU] in ITScope_CompData_temp) are indexed.
Index the extraction_date column in ITScope_CompData_temp.
Temporary Tables:
If ITScope_CompData_temp is large, consider filtering it into a temporary table first to reduce the number of rows before joining with stockinfo.
Batch Processing:
If the query is still slow, consider processing the data in smaller batches (e.g., by splitting the ITScope_CompData_temp table into smaller chunks based on batchname or other criteria).
Expected Output
The query will now return only the rows where there is a match between ITScope_CompData_temp and stockinfo, ensuring that you only see items that exist in the ITScope_CompData_temp table.
User
-- Step 1: Get the latest extraction date
DECLARE @LatestDate VARCHAR(8)
SELECT @LatestDate = MAX(extraction_date)
FROM [Controlling].[dbo].[ITScope_CompData_temp]
-- Step 2: Filter ITScope data with proper matching based on batch
SELECT
cd.manufacturerSKU,
cd.supplierSKU,
cd.supplierName,
cd.manufacturerName,
TRY_CAST(cd.price AS DECIMAL(18, 2)) AS Competitor_Price_EUR,
TRY_CAST(cd.stock AS DECIMAL(18, 2)) AS Competitor_Stock,
cd.extraction_date,
cd.batchname,
s.[No.] AS ItemNo,
s.[Manufacturer Part No],
s.[Stock] AS EET_Stock
INTO #ITSCOPE_Joined
FROM [Controlling].[dbo].[ITScope_CompData_temp] cd
LEFT JOIN [Controlling].[dbo].[stockinfo] s
ON (
(cd.batchname = 'C00' AND cd.supplierSKU = s.[Manufacturer Part No])
OR
(cd.batchname <> 'C00' AND cd.supplierSKU = s.[No.])
)
WHERE cd.extraction_date = @LatestDate
AND ISNUMERIC(cd.price) = 1
AND ISNUMERIC(cd.stock) = 1
-- Step 3: Add cost prices from WebDE in EUR (no conversion needed)
SELECT
i.*,
cp.CostPrice,
cp.CostPriceExclCPct,
cp.Date AS CostPriceDate,
cp.VendorPrice
INTO #ITSCOPE_WithCost
FROM #ITSCOPE_Joined i
LEFT JOIN [WebDE].[dbo].[Costprices] cp
ON i.ItemNo = cp.ItemNo
-- Step 4: Rank all competitor offers per manufacturerSKU
WITH RankedCompetitors AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY manufacturerSKU ORDER BY Competitor_Price_EUR ASC) AS PriceRank
FROM #ITSCOPE_WithCost
)
-- Step 5: Select only Rank 1
SELECT *
INTO #Rank1_Competitor
FROM RankedCompetitors
WHERE PriceRank = 1
-- Step 6: Join EET offer with Rank 1 competitor
SELECT
eet.ItemNo,
eet.manufacturerSKU,
eet.Competitor_Price_EUR AS EET_Price,
eet.EET_Stock,
eet.CostPrice,
r1.supplierName AS Rank1_Competitor,
r1.Competitor_Price_EUR AS Rank1_Price,
r1.Competitor_Stock AS Rank1_Stock
FROM #ITSCOPE_WithCost eet
JOIN #Rank1_Competitor r1
ON eet.manufacturerSKU = r1.manufacturerSKU
WHERE eet.supplierName = 'EET Deutschland'
Msg 319, Level 15, State 1, Line 44
Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon.
The error you're encountering is due to the fact that SQL Server requires a semicolon (;) to terminate the statement preceding a Common Table Expression (CTE). In your case, the WITH RankedCompetitors AS (...) CTE is not preceded by a semicolon, which causes the syntax error.
Root Cause
SQL Server mandates that any statement prior to a CTE must be terminated with a semicolon. This is especially important when using CTEs because they are treated as part of the same batch as the preceding statement.
Solution
To fix this issue, ensure that the statement before the CTE is explicitly terminated with a semicolon. Here's the corrected version of your script:
Corrected Script
-- Step 1: Get the latest extraction date
DECLARE @LatestDate VARCHAR(8);
SELECT @LatestDate = MAX(extraction_date)
FROM [Controlling].[dbo].[ITScope_CompData_temp];
-- Step 2: Filter ITScope data with proper matching based on batch
SELECT
cd.manufacturerSKU,
cd.supplierSKU,
cd.supplierName,
cd.manufacturerName,
TRY_CAST(cd.price AS DECIMAL(18, 2)) AS Competitor_Price_EUR,
TRY_CAST(cd.stock AS DECIMAL(18, 2)) AS Competitor_Stock,
cd.extraction_date,
cd.batchname,
s.[No.] AS ItemNo,
s.[Manufacturer Part No],
s.[Stock] AS EET_Stock
INTO #ITSCOPE_Joined
FROM [Controlling].[dbo].[ITScope_CompData_temp] cd
LEFT JOIN [Controlling].[dbo].[stockinfo] s
ON (
(cd.batchname = 'C00' AND cd.supplierSKU = s.[Manufacturer Part No])
OR
(cd.batchname <> 'C00' AND cd.supplierSKU = s.[No.])
)
WHERE cd.extraction_date = @LatestDate
AND ISNUMERIC(cd.price) = 1
AND ISNUMERIC(cd.stock) = 1;
-- Step 3: Add cost prices from WebDE in EUR (no conversion needed)
SELECT
i.*,
cp.CostPrice,
cp.CostPriceExclCPct,
cp.Date AS CostPriceDate,
cp.VendorPrice
INTO #ITSCOPE_WithCost
FROM #ITSCOPE_Joined i
LEFT JOIN [WebDE].[dbo].[Costprices] cp
ON i.ItemNo = cp.ItemNo;
-- Step 4: Rank all competitor offers per manufacturerSKU
-- FIX: Add a semicolon before the CTE
WITH RankedCompetitors AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY manufacturerSKU ORDER BY Competitor_Price_EUR ASC) AS PriceRank
FROM #ITSCOPE_WithCost
)
-- Step 5: Select only Rank 1
SELECT *
INTO #Rank1_Competitor
FROM RankedCompetitors
WHERE PriceRank = 1;
-- Step 6: Join EET offer with Rank 1 competitor
SELECT
eet.ItemNo,
eet.manufacturerSKU,
eet.Competitor_Price_EUR AS EET_Price,
eet.EET_Stock,
eet.CostPrice,
r1.supplierName AS Rank1_Competitor,
r1.Competitor_Price_EUR AS Rank1_Price,
r1.Competitor_Stock AS Rank1_Stock
FROM #ITSCOPE_WithCost eet
JOIN #Rank1_Competitor r1
ON eet.manufacturerSKU = r1.manufacturerSKU
WHERE eet.supplierName = 'EET Deutschland';
Key Changes
User
-- Step 1: Get the latest extraction date
DECLARE @LatestDate VARCHAR(8);
SELECT @LatestDate = MAX(extraction_date)
FROM [Controlling].[dbo].[ITScope_CompData_temp];
-- Step 2: Filter ITScope data with proper matching based on batch
SELECT
cd.manufacturerSKU,
cd.supplierSKU,
cd.supplierName,
cd.manufacturerName,
TRY_CAST(cd.price AS DECIMAL(18, 2)) AS Competitor_Price_EUR,
TRY_CAST(cd.stock AS DECIMAL(18, 2)) AS Competitor_Stock,
cd.extraction_date,
cd.batchname,
s.[No.] AS ItemNo,
s.[Manufacturer Part No],
s.[Stock] AS EET_Stock
INTO #ITSCOPE_Joined
FROM [Controlling].[dbo].[ITScope_CompData_temp] cd
LEFT JOIN [Controlling].[dbo].[stockinfo] s
ON (
(cd.batchname = 'C00' AND cd.supplierSKU = s.[Manufacturer Part No])
OR
(cd.batchname <> 'C00' AND cd.supplierSKU = s.[No.])
)
WHERE cd.extraction_date = @LatestDate
AND ISNUMERIC(cd.price) = 1
AND ISNUMERIC(cd.stock) = 1;
-- Step 3: Add cost prices from WebDE in EUR (no conversion needed)
SELECT
i.*,
cp.CostPrice,
cp.CostPriceExclCPct,
cp.Date AS CostPriceDate,
cp.VendorPrice
INTO #ITSCOPE_WithCost
FROM #ITSCOPE_Joined i
LEFT JOIN [WebDE].[dbo].[Costprices] cp
ON i.ItemNo = cp.ItemNo;
-- Step 4: Rank all competitor offers per manufacturerSKU
-- FIX: Add a semicolon before the CTE
WITH RankedCompetitors AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY manufacturerSKU ORDER BY Competitor_Price_EUR ASC) AS PriceRank
FROM #ITSCOPE_WithCost
)
-- Step 5: Select only Rank 1
SELECT *
INTO #Rank1_Competitor
FROM RankedCompetitors
WHERE PriceRank = 1;
-- Step 6: Join EET offer with Rank 1 competitor
SELECT
eet.ItemNo,
eet.manufacturerSKU,
eet.Competitor_Price_EUR AS EET_Price,
eet.EET_Stock,
eet.CostPrice,
r1.supplierName AS Rank1_Competitor,
r1.Competitor_Price_EUR AS Rank1_Price,
r1.Competitor_Stock AS Rank1_Stock
FROM #ITSCOPE_WithCost eet
JOIN #Rank1_Competitor r1
ON eet.manufacturerSKU = r1.manufacturerSKU
WHERE eet.supplierName = 'EET Deutschland';
can you improve performance in this code?
Assistant
Improving the performance of your SQL script involves optimizing each step to reduce execution time, minimize resource usage, and handle large datasets efficiently. Below are several strategies to enhance the performance of your code:
1. Optimize Indexing
Indexes are critical for speeding up joins, filters, and aggregations. Ensure that the following columns are indexed:
ITScope_CompData_temp:
extraction_date
batchname
supplierSKU
price (if frequently queried)
stock (if frequently queried)
stockinfo:
[No.]
[Manufacturer Part No]
Costprices:
ItemNo
If these indexes do not exist, create them. For example:
CREATE INDEX IX_ITScope_ExtractionDate ON [Controlling].[dbo].[ITScope_CompData_temp](extraction_date);
CREATE INDEX IX_stockinfo_No ON [Controlling].[dbo].[stockinfo]([No.]);
CREATE INDEX IX_Costprices_ItemNo ON [WebDE].[dbo].[Costprices](ItemNo);
2. Use Temporary Tables with Indexes
Temporary tables can benefit from indexes, especially when they are reused in subsequent queries. After creating a temporary table, add an index on the columns used in joins or filters.
For example:
-- Step 2: Filter ITScope data
SELECT
cd.manufacturerSKU,
cd.supplierSKU,
cd.supplierName,
cd.manufacturerName,
TRY_CAST(cd.price AS DECIMAL(18, 2)) AS Competitor_Price_EUR,
TRY_CAST(cd.stock AS DECIMAL(18, 2)) AS Competitor_Stock,
cd.extraction_date,
cd.batchname,
s.[No.] AS ItemNo,
s.[Manufacturer Part No],
s.[Stock] AS EET_Stock
INTO #ITSCOPE_Joined
FROM [Controlling].[dbo].[ITScope_CompData_temp] cd
LEFT JOIN [Controlling].[dbo].[stockinfo] s
ON (
(cd.batchname = 'C00' AND cd.supplierSKU = s.[Manufacturer Part No])
OR
(cd.batchname <> 'C00' AND cd.supplierSKU = s.[No.])
)
WHERE cd.extraction_date = @LatestDate
AND ISNUMERIC(cd.price) = 1
AND ISNUMERIC(cd.stock) = 1;
-- Add an index to the temporary table
CREATE INDEX IX_ITSCOPE_Joined_ManufacturerSKU ON #ITSCOPE_Joined(manufacturerSKU);
Repeat this for other temporary tables (#ITSCOPE_WithCost and #Rank1_Competitor).
Semicolon Before the CTE:
Added a semicolon (;) at the end of the statement preceding the WITH RankedCompetitors AS (...) CTE.
This ensures compliance with SQL Server's requirement for terminating statements before a CTE.
Consistent Semicolon Usage:
While not strictly necessary for all statements, adding semicolons after each query improves readability and avoids potential issues in future modifications.
Additional Notes
ISNUMERIC Function:
The ISNUMERIC function can sometimes return 1 for values that are not strictly numeric (e.g., currency symbols like $ or scientific notation like 1e3). If you encounter unexpected behavior, consider replacing ISNUMERIC with TRY_CAST or TRY_CONVERT, which are more robust.
Example:
AND TRY_CAST(cd.price AS DECIMAL(18, 2)) IS NOT NULL
AND TRY_CAST(cd.stock AS DECIMAL(18, 2)) IS NOT NULL
Performance Considerations:
Ensure that the columns used in joins (supplierSKU, ItemNo, etc.) and filters (extraction_date) are indexed to optimize query performance.
If the dataset is large, consider creating indexes on temporary tables (#ITSCOPE_Joined, #ITSCOPE_WithCost, etc.) to speed up subsequent queries.
Temporary Tables Cleanup:
Temporary tables (#ITSCOPE_Joined, #ITSCOPE_WithCost, #Rank1_Competitor) are automatically dropped when the session ends. However, if you're running this script multiple times in the same session, you may want to explicitly drop them at the beginning of the script to avoid conflicts.
Example:
IF OBJECT_ID('tempdb..#ITSCOPE_Joined') IS NOT NULL DROP TABLE #ITSCOPE_Joined;
IF OBJECT_ID('tempdb..#ITSCOPE_WithCost') IS NOT NULL DROP TABLE #ITSCOPE_WithCost;
IF OBJECT_ID('tempdb..#Rank1_Competitor') IS NOT NULL DROP TABLE #Rank1_Competitor;
Expected Output
The script will now execute without errors and produce the desired result:
A ranked list of competitors for each manufacturerSKU.
A comparison between EET's offer and the best-ranked competitor's offer.
Let me know if you need further assistance!
3. Replace ISNUMERIC with TRY_CAST
The ISNUMERIC function is not always reliable because it can return 1 for values like $, ., or 1e3. Replace it with TRY_CAST, which is more precise:
AND TRY_CAST(cd.price AS DECIMAL(18, 2)) IS NOT NULL
AND TRY_CAST(cd.stock AS DECIMAL(18, 2)) IS NOT NULL
This ensures that only valid numeric values are included.
4. Filter Data Early
Reduce the size of intermediate results by filtering as early as possible. For example, in Step 2, filter ITScope_CompData_temp before joining with stockinfo. This reduces the number of rows processed during the join.
5. Avoid Unnecessary Columns
Only select the columns you need in each step. Including unnecessary columns increases memory usage and slows down processing.
For example, in Step 2, ensure that only the required columns are selected:
SELECT
cd.manufacturerSKU,
cd.supplierSKU,
cd.supplierName,
cd.manufacturerName,
TRY_CAST(cd.price AS DECIMAL(18, 2)) AS Competitor_Price_EUR,
TRY_CAST(cd.stock AS DECIMAL(18, 2)) AS Competitor_Stock,
cd.extraction_date,
cd.batchname,
s.[No.] AS ItemNo,
s.[Manufacturer Part No],
s.[Stock] AS EET_Stock
INTO #ITSCOPE_Joined
FROM [Controlling].[dbo].[ITScope_CompData_temp] cd
LEFT JOIN [Controlling].[dbo].[stockinfo] s
ON (
(cd.batchname = 'C00' AND cd.supplierSKU = s.[Manufacturer Part No])
OR
(cd.batchname <> 'C00' AND cd.supplierSKU = s.[No.])
)
WHERE cd.extraction_date = @LatestDate
AND TRY_CAST(cd.price AS DECIMAL(18, 2)) IS NOT NULL
AND TRY_CAST(cd.stock AS DECIMAL(18, 2)) IS NOT NULL;
6. Optimize Joins
Use INNER JOIN instead of LEFT JOIN if you only want matching rows. This reduces the number of rows processed.
Ensure that the join conditions are as specific as possible to avoid unnecessary comparisons.
For example, in Step 2, replace LEFT JOIN with INNER JOIN if you only care about matches:
INNER JOIN [Controlling].[dbo].[stockinfo] s
ON (
(cd.batchname = 'C00' AND cd.supplierSKU = s.[Manufacturer Part No])
OR
(cd.batchname <> 'C00' AND cd.supplierSKU = s.[No.])
)
7. Use Window Functions Efficiently
In Step 4, the ROW_NUMBER() function is used to rank competitors. Ensure that the PARTITION BY and ORDER BY clauses are optimized:
WITH RankedCompetitors AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY manufacturerSKU ORDER BY Competitor_Price_EUR ASC) AS PriceRank
FROM #ITSCOPE_WithCost
)
If manufacturerSKU has high cardinality (many unique values), ensure that it is indexed to speed up the partitioning process.
8. Drop Temporary Tables When Done
If you reuse the same script multiple times in the same session, explicitly drop temporary tables at the beginning to avoid conflicts:
IF OBJECT_ID('tempdb..#ITSCOPE_Joined') IS NOT NULL DROP TABLE #ITSCOPE_Joined;
IF OBJECT_ID('tempdb..#ITSCOPE_WithCost') IS NOT NULL DROP TABLE #ITSCOPE_WithCost;
IF OBJECT_ID('tempdb..#Rank1_Competitor') IS NOT NULL DROP TABLE #Rank1_Competitor;
9. Analyze Query Execution Plan
Use SQL Server's Execution Plan to identify bottlenecks:
Look for expensive operations like table scans or hash joins.
Ensure that indexes are being used effectively.
Check for missing indexes or redundant computations.
To view the execution plan:
In SQL Server Management Studio (SSMS), click Include Actual Execution Plan before running the query.
10. Batch Processing for Large Datasets
If the dataset is extremely large, consider processing it in smaller batches. For example, split the data by batchname or another logical grouping:
DECLARE @BatchName NVARCHAR(10) = 'C00';
SELECT ...
FROM [Controlling].[dbo].[ITScope_CompData_temp] cd
WHERE cd.batchname = @BatchName
AND cd.extraction_date = @LatestDate;
Repeat for other batch names.
Final Optimized Script
Here’s the optimized version of your script:
-- Step 1: Get the latest extraction date
DECLARE @LatestDate VARCHAR(8);
SELECT @LatestDate = MAX(extraction_date)
FROM [Controlling].[dbo].[ITScope_CompData_temp];
-- Step 2: Filter ITScope data with proper matching based on batch
IF OBJECT_ID('tempdb..#ITSCOPE_Joined') IS NOT NULL DROP TABLE #ITSCOPE_Joined;
SELECT
cd.manufacturerSKU,
cd.supplierSKU,
cd.supplierName,
cd.manufacturerName,
TRY_CAST(cd.price AS DECIMAL(18, 2)) AS Competitor_Price_EUR,
TRY_CAST(cd.stock AS DECIMAL(18, 2)) AS Competitor_Stock,
cd.extraction_date,
cd.batchname,
s.[No.] AS ItemNo,
s.[Manufacturer Part No],
s.[Stock] AS EET_Stock
INTO #ITSCOPE_Joined
FROM [Controlling].[dbo].[ITScope_CompData_temp] cd
INNER JOIN [Controlling].[dbo].[stockinfo] s
ON (
(cd.batchname = 'C00' AND cd.supplierSKU = s.[Manufacturer Part No])
OR
(cd.batchname <> 'C00' AND cd.supplierSKU = s.[No.])
)
WHERE cd.extraction_date = @LatestDate
AND TRY_CAST(cd.price AS DECIMAL(18, 2)) IS NOT NULL
AND TRY_CAST(cd.stock AS DECIMAL(18, 2)) IS NOT NULL;
CREATE INDEX IX_ITSCOPE_Joined_ManufacturerSKU ON #ITSCOPE_Joined(manufacturerSKU);
-- Step 3: Add cost prices from WebDE in EUR (no conversion needed)
IF OBJECT_ID('tempdb..#ITSCOPE_WithCost') IS NOT NULL DROP TABLE #ITSCOPE_WithCost;
SELECT
i.*,
cp.CostPrice,
cp.CostPriceExclCPct,
cp.Date AS CostPriceDate,
cp.VendorPrice
INTO #ITSCOPE_WithCost
FROM #ITSCOPE_Joined i
LEFT JOIN [WebDE].[dbo].[Costprices] cp
ON i.ItemNo = cp.ItemNo;
CREATE INDEX IX_ITSCOPE_WithCost_ManufacturerSKU ON #ITSCOPE_WithCost(manufacturerSKU);
-- Step 4: Rank all competitor offers per manufacturerSKU
;WITH RankedCompetitors AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY manufacturerSKU ORDER BY Competitor_Price_EUR ASC) AS PriceRank
FROM #ITSCOPE_WithCost
)
-- Step 5: Select only Rank 1
IF OBJECT_ID('tempdb..#Rank1_Competitor') IS NOT NULL DROP TABLE #Rank1_Competitor;
SELECT *
INTO #Rank1_Competitor
FROM RankedCompetitors
WHERE PriceRank = 1;
-- Step 6: Join EET offer with Rank 1 competitor
SELECT
eet.ItemNo,
eet.manufacturerSKU,
eet.Competitor_Price_EUR AS EET_Price,
eet.EET_Stock,
eet.CostPrice,
r1.supplierName AS Rank1_Competitor,
r1.Competitor_Price_EUR AS Rank1_Price,
r1.Competitor_Stock AS Rank1_Stock
FROM #ITSCOPE_WithCost eet
JOIN #Rank1_Competitor r1
ON eet.manufacturerSKU = r1.manufacturerSKU
WHERE eet.supplierName = 'EET Deutschland';
Expected Improvements
Reduced execution time due to efficient indexing and filtering.
Lower memory usage by selecting only necessary columns.
Improved scalability for large datasets.
Let me know if you need further clarification or assistance!