我在将SQL查询转换为Linq(尤其是在“分组依据”部分中)时遇到问题。
SQL:
SELECT
year(ord.OrderDT) as ODate1,
month(ord.OrderDT) as ODate2,
cus.Company as Company,
sum(ord.InvoiceTotal) as TotalRate,
count(ord.InvoiceTotal) as CountOrd
FROM [dbo].[Customer] as cus
join [dbo].[Order] as ord on cus.CustomerID=ord.CustomerID
group by year(ord.OrderDT), month(ord.OrderDT), Company
order by ODate1 desc, ODate2 desc, Company
我尝试过:
var result = (from cus in dbf.Customer
join ord in dbf.Order on cus.CustomerId equals ord.CustomerId
select new {
Year=ord.OrderDt.Year,
Month=ord.OrderDt.Month,
Company=cus.Company,
Rate=ord.InvoiceTotal
} into t1
group t1 by new {t1.Year, t1.Month,t1.Company} into t2
select new
{
Year=t2.FirstOrDefault().Year,
Month=t2.FirstOrDefault().Month,
Customer=t2.FirstOrDefault().Company,
TotalRate=t2.Sum(c=>c.Rate)
}
).Take(10).ToList();
但是我收到错误消息:“。FirstOrDefault()'无法翻译。要么以可以翻译的形式重写查询”。如果我尝试摆脱“ FirstOrDefault”,那么我就没有t2的智能感知
实体:
public Customer()
{
public int CustomerId { get; set; }
public string Company { get; set; }
}
public Order()
{
public int OrderNo { get; set; }
public int CustomerId { get; set; }
public DateTime OrderDT { get; set; }
public decimal InvoiceTotal { get; set; }
}
答案 0 :(得分:0)
尝试下一条选择语句:
select new
{
Year=t2.Key.Year,
Month=t2.Key.Month,
Customer=t2.Key.Company,
TotalRate=t2.Sum(c=>c.Rate)
}
答案 1 :(得分:0)
最终查询如下。
var result = (from cus in dbf.Customer
join ord in dbf.Order on cus.CustomerId equals ord.CustomerId
select new {
Year=ord.OrderDt.Year,
Month=ord.OrderDt.Month,
Company=cus.Company,
Rate=ord.InvoiceTotal
} into t1
group t1 by new {t1.Year, t1.Month,t1.Company} into t2
orderby t2.Key.Year descending, t2.Key.Month descending,t2.Key.Company ascending
select new
{
Year=t2.Key.Year,
Month=t2.Key.Month,
Customer=t2.Key.Company,
TotalRate=t2.Sum(c=>c.Rate),
Count=t2.Count()
}
).ToList();