gpt4 book ai didi

c# - SQL to LINQ with Case .. When in Order By

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:34 24 4
gpt4 key购买 nike

我有一个 SQL 查询,我想将其转换为 LINQ 查询,但我不确定如何继续。我有两个实体 ProductPricePrice 通过 ProductId 链接到 Product。该查询根据请求的Product 数量获取产品的最佳价格。

例如:如果客户想要购买 10 件产品,则该产品的价格可能为 5 美元/件。但是,如果客户想要购买 100 件产品,那么成本可能是 3 美元/件。此查询将根据请求的数量获得最佳单价。 WHERE 子句确保选择了正确的产品,并在日期过期时排除任何价格。 CASE 语句对价格进行排序,以便在达到请求的数量时首先显示最佳价格。

Price Table
--------------------------
Id ProductId Quantity Price BeginDate EndDate
=========================================================================
1 1234 10 $5 1/1/2016 2/1/2016
2 1234 100 $3 1/1/2016 2/1/2016
3 1234 100 $1 1/1/2016 1/9/2016
4 1234 500 $2 1/1/2016 2/1/2016



SELECT TOP 1
Product.Id,
Product.Name,
Prices.Price
FROM Products INNER JOIN Prices ON Products.Id = Prices.ProductId
WHERE Product.Id = @ProductId
AND ((Price.BeginDate IS NULL OR Price.BeginDate < GETDATE()) AND (Price.EndDate IS NULL OR Price.EndDate > GETDATE()))
ORDER BY
CASE WHEN Price.Quantity <= @RequestedQuantity THEN Price.Quantity
ELSE -Price.Quantity
END

在 LINQ 中让我感到困惑的查询部分 ..

  1. 如何过滤掉价格日期已过期的价格(例如 Id = 3)。
  2. 如何使用 case 语句对集合进行排序。

一旦这些准备就绪,我就可以使用 FirstOrDefault

选择最靠前的结果

最佳答案

尝试使用 let 关键字来定义列并对其进行排序。我没有测试它,我不确定它是否会像您期望的那样工作。确保您在其上定义了所有实体和属性,例如:

var query = from product in Products 
join price in Prices on product.Id equals price.ProductId
let priceOrder = price.Quantity <= requestValue ? price.Quantity : -price.Quantity
where ((price.BeginDate == null || Price.BeginDate < DateTime.Now) && (Price.EndDate == null || Price.EndDate > DateTime.Now))
orderby priceOrder
select { product.Id, product.Name, price.Price };

var result = query.FirstOrDefault();

关于c# - SQL to LINQ with Case .. When in Order By,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34929256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com