访问查询:按逻辑排序日期,而不是按字母顺序排序

时间:2015-03-12 19:20:23

标签: sql ms-access ms-access-2010 jet

查询的SQL是:

SELECT DISTINCTROW Format$([Client Accounting].[Closing Date],'mmmm') AS [Month], Count([Client Accounting].[Loan Number]) AS [DB Error #], Sum([Client Accounting].[Write Off]) AS [Write Off], Sum([Client Accounting].Refund) AS Refund
FROM [Client Accounting]
GROUP BY Format$([Client Accounting].[Closing Date],'mmmm'), Year([Client Accounting].[Closing Date])*12+DatePart('m',[Client Accounting].[Closing Date])-1
ORDER BY Format$([Client Accounting].[Closing Date],'mmmm'), Year([Client Accounting].[Closing Date])*12+DatePart('m',[Client Accounting].[Closing Date])-1;

结果如下数据表:

DB

  • 上述月份为:12-14,1-15,2-15,3-15
  • 查询分组/排序的[结算日期]字段是格式为m / d / yyyy的日期/时间字段(例如12/1/2014或2015年3月26日)

如您所见,月份按字母顺序排序,而非逻辑排序。是否有人能够建议我如何修改我的SQL以按日期格式 mm (数字格式的月份)对查询进行分组/排序,但在数据表/报告中显示为 mmmm < / em>(文本中的月份名称)。

2 个答案:

答案 0 :(得分:3)

将每月第一天的字段表达式添加到SELECT列表和GROUP BY子句中。

DateSerial(Year([Closing Date]), Month([Closing Date]), 1) AS Month_Start

然后你可以ORDER BY计算字段。

如果您不希望该字段出现在查询输出中,您可以在子查询中使用它 - 计算后的字段可以用于ORDER BY但可以从父查询中排除{ {1}}列表。

SELECT

注意:

  1. SELECT sub.Month, sub.[DB Error #], sub.[Write Off], sub.Refund FROM ( SELECT DateSerial(Year(ca.[Closing Date]), Month(ca.[Closing Date]), 1) AS Month_Start, Format$(ca.[Closing Date],'mmmm') AS [Month], Count(ca.[Loan Number]) AS [DB Error #], Sum(ca.[Write Off]) AS [Write Off], Sum(ca.Refund) AS Refund FROM [Client Accounting] AS ca GROUP BY DateSerial(Year(ca.[Closing Date]), Month(ca.[Closing Date]), 1), Format$(ca.[Closing Date],'mmmm') ) AS sub ORDER BY sub.Month_Start; DISTINCTROW查询中没用,因为根据定义,查询的输出行已经是唯一的。
  2. 您可以使用其他GROUP BY表达式代替我建议的Format表达式,例如DateSerial

答案 1 :(得分:0)

如果您的原始查询除排序外有效,那么您只需按月份分组:

SELECT 
    Format([Client Accounting].[Closing Date],'mmmm') AS [Month], 
    Count([Client Accounting].[Loan Number]) AS [DB Error #], 
    Sum([Client Accounting].[Write Off]) AS [Write Off], 
    Sum([Client Accounting].Refund) AS Refund
FROM 
    [Client Accounting]
GROUP BY 
    DateSerial(Year([Client Accounting].[Closing Date]), Month([Client Accounting].[Closing Date], 1),
    Format([Client Accounting].[Closing Date],'mmmm')