I have the following query, I modified it to be able to look in a new table called Futuredial_Validation, I wrote all the conditions and the joins but its still don't looking in the table, just in the one called cellscripter, the rest of the query works, I really appreciate any help, thanks:
SELECT row_number() OVER (ORDER BY wms_us.wms_us.rrno.rrdate, wms_us.wms_us.rrno.pono, wms_us.wms_us.transferboxdet.meidhex, att.Date_cleared) AS ROW_ID,
wms_us.wms_us.rrno.pono AS ATT_PO,
wms_us.wms_us.rrno.rrdate AS Received_Date,
CASE
WHEN (wms_us.wms_us.model.modeldesc = 'MIXED')
THEN wms_us.wms_us.transferboxdet.basemodel
ELSE wms_us.wms_us.model.modelbase
END AS Model,
CASE
WHEN LEN(wms_us.wms_us.transferboxdet.meidhex) >= 15
THEN LEFT(wms_us.wms_us.transferboxdet.meidhex, 14)
ELSE wms_us.wms_us.transferboxdet.meidhex
END AS IMEI,
/*Check in Futerdial else obtain the values from cellscripter*/
CASE
WHEN (Future.[Error Code] = '1')
THEN Future.LocalTime
ELSE att.Date_cleared
END AS Date_cleared,
CASE
WHEN (Future.[Error Code] = '1')
THEN 'PASS'
ELSE att.Result
END AS Result
FROM wms_us.wms_us.transferboxdoc
INNER JOIN wms_us.wms_us.transferboxdet
ON wms_us.wms_us.transferboxdoc.transferboxdocid = wms_us.wms_us.transferboxdet.transferboxdocid
INNER JOIN wms_us.wms_us.rrno
ON wms_us.wms_us.transferboxdet.rrnoid = wms_us.wms_us.rrno.rrnoid
INNER JOIN wms_us.wms_us.model
ON wms_us.wms_us.transferboxdoc.modelid = wms_us.wms_us.model.modelid
LEFT OUTER JOIN Futerdial.dbo.Futuredial_Validation AS Future
ON Future.IMEI = LEFT(wms_us.wms_us.transferboxdet.meidhex, 14)
LEFT OUTER JOIN DRSCSQLQADB01.att_view2.dbo.attview2 AS att
ON att.IMEI = LEFT(wms_us.wms_us.transferboxdet.meidhex, 14)
WHERE (wms_us.wms_us.rrno.rrdate > '2016-12-01')
Most likely: either your join specification is not working or the case expression for the [Error Code] is not correct.
Check if you get any values for [Future_imei] and [Error Code] with this:
select
row_id = row_number() over (
order by rrno.rrdate
, rrno.pono
, tbdet.meidhex
, att.Date_cleared)
, att_po = rrno.pono
, Received_Date = rrno.rrdate
, Model=case
when (m.modeldesc = 'mixed')
then tbdet.basemodel
else m.modelbase
end
, imei=case
when len(tbdet.meidhex) >= 15
then left(tbdet.meidhex, 14)
else tbdet.meidhex
end
, [Future_imei] = Future.imei
, Future.[Error Code]
, Date_cleared=case
when (Future.[Error Code] = '1')
then Future.LocalTime
else att.Date_cleared
end
, [Result]=case
when (Future.[Error Code] = '1')
then 'pass'
else att.Result
end
from wms_us.wms_us.transferboxdoc as tbdoc
inner join wms_us.wms_us.transferboxdet as tbdet
on tbdoc.transferboxdocid = tbdet.transferboxdocid
inner join wms_us.wms_us.rrno as rrno
on tbdet.rrnoid = rrno.rrnoid
inner join wms_us.wms_us.model as m
on tbdoc.modelid = m.modelid
left outer join Futerdial.dbo.Futuredial_Validation as Future
on Future.imei = left(tbdet.meidhex, 14)
left outer join drscsqlqadb01.att_view2.dbo.attview2 as att
on att.imei = left(tbdet.meidhex, 14)
where (rrno.rrdate > '2016-12-01')
Having some issues displaying a calculated column.
I'm displaying a line for parent, then a few (anywhere between 1-5) lines for each child item.
My first query is this:
Select
_r1 = pbhier.r1
, pb.parent_id
, pb.Product_id
, pb.LastCost
, pb.AverageCost
, pb.FirstDatePurchased
, lrd.LastReceivingDate
, inv_units = isnull(inv.quantity,0)
, sales_units = convert(int,isnull(sales.SalesUnits,0))
, number_months_supply = case when isnull(sales.salesUnits,0) = 0 then isnull(inv.quantity,0)
else
case when (isnull(sales.salesUnits,0)/12) = 0 then 0
else
(convert(int,(inv.quantity/(isnull(sales.salesUnits,0)/12)))) end end
, inv.quantity, sales.SalesUnits
, ext_AverageCost = isnull(inv.quantity,0) * pb.averagecost
INTO #tempdata
From Products pb
inner join #TempFinalHier pbhier on pb.product_id = pbhier.product_id
left join #inventoryPC inv (nolock) on pb.product_id = inv.product_id
left join #tempTotSalesPC sales (nolock) on pb.product_id = sales.product_id
left join #lastReceivingDate lrd on lrd.rm_product_id = pb.product_id
where pb.Parent_ID in (select parent_id from #FinalParentSelection)
This creates a temp data set. The column "number_months_supply" does not need to be calculated above but the same formula should be used in my final query. My final query below gets me the final result set:
Select distinct
H.R1 , H.R2, H.Lvl,
case
when R1 <> R2
then H.parent_sku
else H.SKU
end as SKU,
H.parent_sku,
FirstReceiptDate = min(B.FirstDatePurchased),
LastReceiptDate = max(B.LastReceivingDate),
OnHand = sum(B.inv_units),
SalesUnits = sum(B.sales_units),
case
when isnull(sum(B.sales_units),0) = 0
then isnull(sum(B.inv_units),0)
else
case
when (isnull(sum(B.sales_units),0)/12) = 0
then 0
else convert(decimal(10, 2), (sum(B.inv_units) / (isnull(sum(B.sales_units), 0) / 12)))
end
end,
max(B.ext_AverageCost) as ext_AverageCost
From
#TempFinalHier H
join
#TempData1 B on (B._R1 between H.R1 and H.R2)
-- where H.Lvl=1 --Show only parent line
Group By
H.R1, H.R2, H.Lvl, H.parent_sku
having
sum(B.number_months_supply) > 12 --#MonthsSupplyGreaterThanOrEqual
Order by
R1
What I'm trying to get is:
'onHand' for parent line (lvl1) needs to be sum of all child rows (lvl2). same applies to 'SalesUnits'. Finally, Number_months_supply formula is (inv/sales_units)*12. I would like to display the number_months_supply as numeric with 2 decimal points.
Would appreciate some help with this.
Thanks.
I am having an MVC4 web application where I am using LINQ.
I have the below query which results 53 rows in SQL.
select * from table1 t join
[table2] tpf on t.TestID=tpf.TestID
join
table3 pf on tpf.Test2ID =pf.Test2ID
join table4 pfp on
pf.Test3ID = pfp.Test3ID
join table5 p on pfp.Test5ID = p.Test5ID where t.testtypeid=1
order by pfp.Test3ID,pf.Test2ID
If I convert the same query as below it returns more records.
trvm.MyTestVMs = (
from tt in db.table1s
join ttpf in db.table2s on tt.TestID equals ttpf.TestID
join pf in db.table3s on ttpf.Test2ID equals pf.Test2ID
join pfp in db.table4s on pf.Test3ID equals pfp.Test3ID
join p in table5s on pfp.Test5ID equals p.Test5ID
where tt.testtypeid == 1
orderby pfp.Test3ID
orderby pf.Test2ID
select new MyTestVM
{
FamilyID = pf.Test2ID,
ProductID = p.Test3ID,
Desc = p.Description
}
).ToList();
The result which is getting from SQL and the above LINQ varies. Actually, there are some duplicate result I am getting from the LINQ query. What is causing this difference?
It turns out that the LINQ query is not equivalent to the SQL query posted due to the usage of a products query variable (not shown in the post) which causes one of the many-to-many link table to be included twice, thus producing more records.
One way to fix the problem is to replace products with db.Products and apply the same filters as in the query variables you were trying to reuse.
But if you want to reuse query variables, then here is the correct way to do that:
// Eliminate the need of DbFunctions.TruncateTime(dt) inside the queries
dt = dt.Date;
// Queries
var productFamilys = (
from tt in db.TestTypes
join ttpf in db.TestTypeProductFamilys on tt.TestTypeID equals ttpf.TestTypeID
join pf in db.ProductFamilys on ttpf.ProductFamilyID equals pf.ProductFamilyID
where tt.TestTypeID == TestTypeID
where DbFunctions.TruncateTime(pf.StartDate) <= dt
where DbFunctions.TruncateTime(pf.EndDate) > dt
select pf
);
var productFamilyProducts = (
from pf in productFamilys
join pfp in db.ProductFamilyProducts on pf.ProductFamilyID equals pfp.ProductFamilyID
join p in db.Products on pfp.ProductID equals p.ProductID
where DbFunctions.TruncateTime(p.StartDate) <= dt
where DbFunctions.TruncateTime(p.EndDate) > dt
select new { Family = pf, Product = p }
);
var products = (
from pfp in productFamilyProducts
select pfp.Product
);
var productFamilyProductVMs = (
from pfp in productFamilyProducts
orderby pfp.Product.ProductID, pfp.Family.ProductFamilyID
select new ProductFamilyProductVM
{
ProductFamilyID = pfp.Family.ProductFamilyID,
ProductID = pfp.Product.ProductID,
ProdDesc = pfp.Product.Description
}
);
// Results
trvm.ProductFamilys = productFamilys.ToList();
trvm.Products = products.ToList();
trvm.ProductFamilyProductVMs = productFamilyProductVMs.ToList();
Now the SQL for the last query (the one in question) looks like this
SELECT
[Project1].[ProductFamilyID] AS [ProductFamilyID],
[Project1].[ProductID] AS [ProductID],
[Project1].[Description] AS [Description]
FROM ( SELECT
[Extent2].[ProductFamilyID] AS [ProductFamilyID],
[Extent4].[ProductID] AS [ProductID],
[Extent4].[Description] AS [Description]
FROM [dbo].[TestTypeProductFamilies] AS [Extent1]
INNER JOIN [dbo].[ProductFamilies] AS [Extent2] ON [Extent1].[ProductFamilyID] = [Extent2].[ProductFamilyID]
INNER JOIN [dbo].[ProductFamilyProducts] AS [Extent3] ON [Extent2].[ProductFamilyID] = [Extent3].[ProductFamilyID]
INNER JOIN [dbo].[Products] AS [Extent4] ON [Extent3].[ProductID] = [Extent4].[ProductID]
WHERE ([Extent1].[TestTypeID] = #p__linq__0) AND ((convert (datetime2, convert(varchar(255), [Extent2].[StartDate], 102) , 102)) <= #p__linq__1) AND ((convert (datetime2, convert(varchar(255), [Extent2].[EndDate], 102) , 102)) > #p__linq__2) AND ((convert (datetime2, convert(varchar(255), [Extent4].[StartDate], 102) , 102)) <= #p__linq__3) AND ((convert (datetime2, convert(varchar(255), [Extent4].[EndDate], 102) , 102)) > #p__linq__4)
) AS [Project1]
ORDER BY [Project1].[ProductID] ASC, [Project1].[ProductFamilyID] ASC
i.e. pretty similar to the sample SQL query and should produce the same results.
Result is different because in your second query , you have two "OrderBy" and because of that, the second OrderBy it's works over the collection which is result of first "OrderBy" and is reordering the items.
Change
orderby pfp.ProductID
orderby pf.ProductFamilyID
from your second query in
orderby pfp.ProductID, pf.ProductFamilyID
to get same results
So I have a few really slow queries in SP's I need to speed up, I have been using OPTIMIZE FOR UNKNOWN and seeing some dramatic increases in performance. I still have one query that really is slow and I want to apply this but it contains a UNION of 2 SQL Queries, so my question is do I apply the OPTIMIZE FOR UNKNOWN to both?
THIS IS A GREATLY SIMPLIFIED VERSION OF MY SP FOR CLARITY:
SELECT * FROM MyTable ManufacturerID=#ManufacturerID and tStamp > #tStamp
OPTION (OPTIMIZE FOR (#ManufacturerID UNKNOWN, #tStamp UNKNOWN))
UNION
SELECT * FROM MyTable ManufacturerID=#ManufacturerID
OPTION (OPTIMIZE FOR (#ManufacturerID UNKNOWN)
Here is the actual SP as it stand right now:
SELECT * FROM (
SELECT ROW_NUMBER() OVER(ORDER BY Products.ItemID) AS RowNum, *
FROM
(
SELECT Products.ProductID, Products.ItemID, Products.ManufacturerID,
CategoryID = NULL, CategoryName = NULL,
CategoryProductID = NULL, Products.ItemName, Products.Description, Products.Notes,
Products.Dimensions, Products.BasePrice, Products.OrderMinimumQuantity,
ContainerMinimumQuantity =
CASE COALESCE(Products.ContainerMinQty, 0)
WHEN 0 THEN Products.OrderMinimumQuantity
ELSE Products.ContainerMinQty
END
, Products.OrderMultipleQuantity, Products.OnHandQuantity,
Products.Category, Products.IntroDate, Products.BackOrderDate, Products.UPC, Products.PriceLevel1, Products.PriceLevel2, Products.PriceLevel3,
Products.PriceLevel4, Products.PriceLevel5, Products.PriceLevel6, Products.PriceLevel7, Products.PriceLevel8, Products.PriceLevel9, Products.PieceBox,
Products.Cubes, Products.UnitOfMeasure, Products.UDF1, Products.UDF2, Products.UDF3, Products.UDF4, Products.UDF5, Products.AdditionalImageCount,
PhotoName= LOWER(Products.PhotoName), Products.Discontinued, Products.ModifiedOn,
Products.IsDeleted, Products.PriceLevel10, Products.PriceLevel11, Products.PriceLevel12, Products.PriceLevel13,
Products.PriceLevel14, Products.PriceLevel15, Products.PriceLevel16, Products.PriceLevel17, Products.PriceLevel18, Products.PriceLevel19, Products.PriceLevel20,
Products.Weight, Products.DimensionsMetric, Products.Source, Products.InventoryStatus, Products.CatalogCode, Products.CatalogName,
SortOrder = NULL,
Products.reportCategory,Products.additionalPhotos,Products.udf6,Products.udf7,Products.udf8,
Products.udf9,Products.udf10,Products.udf11,Products.udf12,Products.udf13,Products.udf14,Products.udf15,Products.udf16,
Products.udf17,Products.udf18,Products.udf19,Products.udf20, Products.showRelatedFor,Products.showChildFor
FROM
CategoryProducts (nolock) RIGHT OUTER JOIN
Products (nolock) ON CategoryProducts.ManufacturerID = Products.ManufacturerID AND CategoryProducts.ItemID = Products.ItemID
WHERE (Products.ManufacturerID = #ManufacturerID)
AND
(Products.ModifiedOn > #tStamp ) AND ((CategoryProducts.IsDeleted = 1) OR (CategoryProducts.IsDeleted IS NULL)
)
UNION
SELECT Products.ProductID, Products.ItemID, Products.ManufacturerID, Categories.CategoryID, Categories.CategoryName, CategoryProducts.CategoryProductID, Products.ItemName, Products.Description, Products.Notes,
Products.Dimensions, Products.BasePrice, Products.OrderMinimumQuantity,
ContainerMinimumQuantity =
CASE COALESCE(Products.ContainerMinQty, 0)
WHEN 0 THEN Products.OrderMinimumQuantity
ELSE Products.ContainerMinQty
END
, Products.OrderMultipleQuantity, Products.OnHandQuantity,
Products.Category, Products.IntroDate, Products.BackOrderDate, Products.UPC, Products.PriceLevel1, Products.PriceLevel2, Products.PriceLevel3,
Products.PriceLevel4, Products.PriceLevel5, Products.PriceLevel6, Products.PriceLevel7, Products.PriceLevel8, Products.PriceLevel9, Products.PieceBox,
Products.Cubes, Products.UnitOfMeasure, Products.UDF1, Products.UDF2, Products.UDF3, Products.UDF4, Products.UDF5, Products.AdditionalImageCount,
PhotoName= LOWER(Products.PhotoName), Products.Discontinued, Products.ModifiedOn,
CategoryProducts.IsDeleted, Products.PriceLevel10, Products.PriceLevel11, Products.PriceLevel12, Products.PriceLevel13,
Products.PriceLevel14, Products.PriceLevel15, Products.PriceLevel16, Products.PriceLevel17, Products.PriceLevel18, Products.PriceLevel19, Products.PriceLevel20,
Products.Weight, Products.DimensionsMetric, Products.Source, Products.InventoryStatus, Products.CatalogCode, Products.CatalogName,
CategoryProducts.SortOrder,
Products.reportCategory,Products.additionalPhotos,Products.udf6,Products.udf7,Products.udf8,
Products.udf9,Products.udf10,Products.udf11,Products.udf12,Products.udf13,Products.udf14,Products.udf15,Products.udf16,
Products.udf17,Products.udf18,Products.udf19,Products.udf20, Products.showRelatedFor,Products.showChildFor
FROM Categories (nolock) INNER JOIN
CategoryProducts (nolock) ON Categories.CategoryID = CategoryProducts.CategoryID INNER JOIN
Products (nolock) ON CategoryProducts.ManufacturerID = Products.ManufacturerID AND CategoryProducts.ItemID = Products.ItemID
WHERE (Products.ManufacturerID = #ManufacturerID)
AND
(Products.ModifiedOn > #tStamp OR CategoryProducts.ModifiedOn > #tStamp)
) AS Products
) AS C WHERE RowNum >= #StartRow AND RowNum <= #EndRow ORDER BY ItemID, ManufacturerID
OPTION (OPTIMIZE FOR (#ManufacturerID UNKNOWN, #StartRow UNKNOWN, #EndRow UNKNOWN, #tStamp UNKNOWN))
From Books Online (Query Hints):
Query hints specify that the indicated hints should be used throughout
the query. They affect all operators in the statement. If UNION is
involved in the main query, only the last query involving a UNION
operation can have the OPTION clause.
So that's pretty explicit that you can only use OPTION once, not twice like in your example.
That makes sense, since even though there are two SELECT statements put together, SQL Server will still treat it as one overall statement for the purposes of compilation and optimization.
This does mean that if you want to use different hints in the different statements that make up the UNION you'll have to go about it a different way, e.g. using TEMP tables to store the interim results.
So, in your specific example, even though #tStamp is only in the first SELECT statement, you can still reference it in the one OPTION clause as required.
Try this one -
SELECT
p.ProductID
, RowNum = ROW_NUMBER() OVER(ORDER BY p.ItemID)
, p.ItemID
, p.ManufacturerID
, CategoryID = NULL
, CategoryName = NULL
, CategoryProductID = NULL
, p.ItemName
, p.[Description]
, p.Notes
, p.Dimensions
, p.BasePrice
, p.OrderMinimumQuantity
, ContainerMinimumQuantity =
CASE WHEN ISNULL(p.ContainerMinQty, 0) = 0
THEN p.OrderMinimumQuantity ELSE p.ContainerMinQty
END
, p.OrderMultipleQuantity
, p.OnHandQuantity
, p.category
, p.IntroDate
, p.BackOrderDate
, p.UPC
...
, p.PieceBox
, p.Cubes
, p.UnitOfMeasure
, p.UDF1, p.UDF2, p.UDF3
, p.UDF4, p.UDF5
, p.AdditionalImageCount
, PhotoName = LOWER(p.PhotoName)
, p.Discontinued
, p.ModifiedOn
, p.IsDeleted
...
, p.[Weight]
, p.DimensionsMetric
, p.[Source]
, p.InventoryStatus
, p.CatalogCode
, p.CatalogName
, SortOrder = NULL
, p.reportCategory
, p.additionalPhotos
....
, p.showRelatedFor
, p.showChildFor
FROM dbo.Products p WITH(NOLOCK)
--LEFT JOIN (
-- SELECT *
-- FROM dbo.CategoryProducts cp WITH(NOLOCK)
-- WHERE ISNULL(cp.IsDeleted, 1) = 1
--) cp ON cp.ManufacturerID = p.ManufacturerID AND cp.ItemID = p.ItemID
WHERE p.ManufacturerID = #ManufacturerID
AND p.ModifiedOn > #tStamp