简体   繁体   English

SQL在MVC查询中按日期分组

[英]SQL group by date in MVC query

I am trying to make a query in my database on mvc, I want to count the purchase id and group by Order date. 我正在尝试在MVC上的数据库中进行查询,我想按订单日期计算购买ID和分组。 this is my purchase model: 这是我的购买模式:

public class Purchase
{
    public int PurchaseID { get; set; }
    public int CustomerID { get; set; }

    public bool DeliveryChoice { get; set; }
    public int? DriverID { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    [Display(Name = "Order Date")]
}

and this is my query: 这是我的查询:

SELECT  
    Purchase.PurchaseID, 
    Purchase.OrderDate,
    COUNT(*) 
From Purchase 
GROUP BY Purchase.OrderDate;

this is the message i get when i execute it: 这是我执行时收到的消息:

Msg 8120, Level 16, State 1, Line 1 消息8120,第16级,状态1,第1行
Column 'Purchase.PurchaseID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. 选择列表中的“ Purchase.PurchaseID”列无效,因为它既不包含在聚合函数中,也不包含在GROUP BY子句中。

How would I fix it to allow me to group by date (yyyy-MM-dd) and count the purchaseid 我将如何解决该问题,以便我按日期分组(yyyy-MM-dd)并计算purchaseid

If you need to count purchaseID groupped by date, then you need query like this one: 如果您需要计算按日期分组的purchaseID,则需要进行如下查询:

select 
    convert(nvarchar(10), Purchase.OrderDate, 112) as OrderDate,  
    count(Purchase.PurchaseID) 
from Purchase 
group by convert(nvarchar(10), Purchase.OrderDate, 112)

Just move Purchase.PurchaseID to the argument of aggregate function count 只需将Purchase.PurchaseID移至聚合函数count的参数即可

You're getting the error you've mentioned because when you're groupping results of query - then every selected value should be either column you're groupping by, or a result of some aggregate function - this is exactly what was stated in error text. 您遇到了提到的错误,因为在对查询结果进行分组时-每个选择的值都应该是您要分组的列,或者是某些聚合函数的结果-这正是错误中所说的文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM