按日期排序不在我的项目中工作

时间:2015-03-19 09:56:33

标签: c# asp.net sql-server-2008

我正在开发一个C#/ ASP.NET项目,我正在使用SQL Server作为我的后端。

我已经写了一个查询来获取每月和每年“总销售额”的详细信息,即mm-yyyy格式,我想按升序排序。

但查询不会按升序对结果进行排序。

我的查询是

/* TOTAL SALE*/
SELECT 
    CAST((Datepart(Month, [p].Transdate)) AS varchar(50)) +'-'+  
    CAST((Datepart(Year, [p].Transdate)) AS varchar(50)) AS [Month/Year],
    SUM([p].Litres) [Total Sale] 
FROM 
    CustomerPoints AS [p] 
INNER JOIN
    Customers AS [c] ON [c].[CustomerID] = [p].[CustomerID] 
WHERE
    [p].Transdate BETWEEN '2013-01-20' AND '2015-03-05' 
    AND [c].DistributorID = '1'
GROUP BY 
    CAST((Datepart(Month, [p].Transdate)) AS varchar(50)) + '-'+ 
    CAST((Datepart(Year, [p].Transdate)) AS varchar(50))
ORDER BY 
    CAST((Datepart(Month, [p].Transdate)) AS varchar(50)) + '-'+ 
    CAST((Datepart(Year, [p].Transdate)) AS varchar(50)) ASC

以上查询的输出为

Month/Year   Total Sale
--------------------------
1-2013          600
1-2014          2300
10-2014         0
2-2015          1560
3-2014          80
3-2015          700

请帮助。

提前谢谢。

2 个答案:

答案 0 :(得分:3)

因为您将日期转换为字符串,所以您会获得字典顺序而不是日期。所以不要施展它:

SELECT Cast((Datepart(month, [p].transdate)) AS VARCHAR(50)) 
       + '-' 
       + Cast((Datepart(year, [p].transdate))AS VARCHAR(50)) AS [Month/Year], 
       Sum([p].litres)                                       [Total Sale] 
FROM   customerpoints AS [p] 
       INNER JOIN customers AS [c] 
               ON [c].[customerid] = [p].[customerid] 
WHERE  [p].transdate BETWEEN '2013-01-20' AND '2015-03-05' 
       AND [c].distributorid = '1' 
GROUP  BY Cast((Datepart(month, [p].transdate)) AS VARCHAR(50)) 
          + '-' 
          + Cast((Datepart(year, [p].transdate))AS VARCHAR(50)) 
ORDER  BY MIN(transdate) ASC 

但是,由于您使用的是Group By,因此您必须告诉SQL-Server您要从transdate获取每个组的哪一行。我只使用了MIN(transdate),这是本月的开始。

答案 1 :(得分:1)

为什么你"格式"您想订购的日期?

Cast((Datepart(Month,[p].Transdate)) as varchar(50)) + '-'+
Cast((Datepart(Year,[p].Transdate))as varchar(50)) ASC

这将关于该部分作为varchar(50)进行排序。只需通过Transdate订购。