在SQL语句中按月分组

时间:2014-01-19 03:49:12

标签: c# asp.net sql-server datetime group-by

我目前正在尝试通过选择SQL语句来创建一个组。我想做的是一年内有12个月。在一个月内,我总结了所有传出的项目并显示为条形图。以下是我设置SQL语句的方法:

public List<ProductPacking> getSumProductByMonth(string prodName)
    {
        List<ProductPacking> ft = new List<ProductPacking>();

        using (var connection = new SqlConnection(FoodBankDB.connectionString))
        {
            SqlCommand command = new SqlCommand("SELECT SUM(Convert(INT, ddi.productQuantity)) AS totalQuantity, p.name, month(d.deliveryDate) AS deliveryMonth FROM dbo.DistributionDistributedItems ddi " +
                " INNER JOIN dbo.ProductVariants pv ON ddi.productVariant = pv.id " +
                " INNER JOIN dbo.Products p ON pv.product = p.id " +
                " INNER JOIN dbo.Distributions d ON ddi.distribution = d.id " +
                " WHERE p.name = '" + prodName + "' AND year(deliveryDate) < GETDATE() " +
                " GROUP BY p.name, month(d.deliveryDate)", connection);
            connection.Open();
            using (var dr = command.ExecuteReader())
            {
                while (dr.Read())
                {
                    DateTime deliveryMonth = DateTime.ParseExact(dr["deliveryMonth"].ToString(), "MMMM", CultureInfo.InvariantCulture);
                    ft.Add(new ProductPacking(Convert.ToInt32(dr["totalQuantity"].ToString()), deliveryMonth));
                }
            }
        }
        return ft;
    }

在调试模式下,它将deliveryMonth返回为1/1/0001 12:00:00 AM,这是不正确的。我确信我在数据库中存储了正确的日期格式。我测试了查询,它返回了正确的数据。只是日期格式化错误。

我尝试将日期格式设置为1月,2月等。但是,它返回一条错误消息,即String未被识别为有效的DateTime。我想知道为什么会这样,因为我设法按年解析这是我的另一个功能。

提前致谢。

1 个答案:

答案 0 :(得分:-1)

使用DATENAME函数更改SQL语句,以按月份名称对数据进行分组:

SqlCommand command = new SqlCommand("SELECT SUM(Convert(INT, ddi.productQuantity)) AS totalQuantity, p.name, DATENAME(MONTH,d.deliveryDate) AS deliveryMonth FROM dbo.DistributionDistributedItems ddi " +
    " INNER JOIN dbo.ProductVariants pv ON ddi.productVariant = pv.id " +
    " INNER JOIN dbo.Products p ON pv.product = p.id " +
    " INNER JOIN dbo.Distributions d ON ddi.distribution = d.id " +
    " WHERE p.name = '" + prodName + "' AND year(deliveryDate) < GETDATE() " +
    " GROUP BY p.name, DATENAME(MONTH,d.deliveryDate)", connection);

并将dr["deliveryMonth"]传递给ProductPacking构造函数:

while (dr.Read())
{
    ft.Add(new ProductPacking(Convert.ToInt32(dr["totalQuantity"].ToString()), dr["deliveryMonth"].ToString()));
}