0

请帮我解决这个简单的 E-sql 查询:

var qStr = "SELECT SqlServer.Month(o.DatePaid) as month, SqlServer.Sum(o.PaidMoney) as PaidMoney FROM XACCModel.OrdersIncomes as o group by SqlServer.Month(o.DatePaid)";

这就是我所拥有的。

我有一个OrdersIncomesID,PaidMoney,DatePaid,Order_ID属性调用的简单实体

我想像这样选择 Month 和 Summed PaidMoney:

month  Paidmoney

1 500

2 700

3 1200

T-SQL looks like this and works fine:

    select MONTH(o.DatePaid), SUM(o.PaidMoney)
    from OrdersIncomes as o
    group by MONTH(o.DatePaid)

results:
-----------

3           31.0000

4           127.0000

5           20.0000

(3 row(s) affected)

但是 E-SQL 不起作用,我不知道该怎么办。这是我需要重构的 E-SQL:

var qStr = "SELECT SqlServer.Month(o.DatePaid) as month, SqlServer.Sum(o.PaidMoney) as PaidMoney FROM XACCModel.OrdersIncomes as o group by SqlServer.Month(o.DatePaid)";

有一个例外:ErrorDescription = "标识符 'o' 无效,因为它既不包含在聚合函数中,也不包含在 GROUP BY 子句中。"

如果我在 group by 子句中包含 o,例如:FROM XACCModel.OrdersIncomes as o group by o 那么我不会得到求和和汇总的结果。这是一个错误,还是我做错了什么?

这是一个 Linq to Entities 查询,它也可以工作:

var incomeResult = from ic in _context.OrdersIncomes
     group ic by ic.DatePaid.Month into gr
     select new { Month = gr.Key, PaidMoney = gr.Sum(i => i.PaidMoney) };
4

1 回答 1

2

为 Group By 子句指定别名并在 select 子句中使用该别名。

SELECT PaidMonth , SqlServer.Sum(o.PaidMoney) as PaidMoney FROM XACCModel.OrdersIncomes as o group by SqlServer.Month(o.DatePaid) as PaidMonth

于 2010-08-17T23:31:50.527 回答