查询的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;
结果如下数据表:
如您所见,月份按字母顺序排序,而非逻辑排序。是否有人能够建议我如何修改我的SQL以按日期格式 mm (数字格式的月份)对查询进行分组/排序,但在数据表/报告中显示为 mmmm < / em>(文本中的月份名称)。
答案 0 :(得分:3)
将每月第一天的字段表达式添加到SELECT
列表和GROUP BY
子句中。
DateSerial(Year([Closing Date]), Month([Closing Date]), 1) AS Month_Start
然后你可以ORDER BY
计算字段。
如果您不希望该字段出现在查询输出中,您可以在子查询中使用它 - 计算后的字段可以用于ORDER BY
但可以从父查询中排除{ {1}}列表。
SELECT
注意:
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
查询中没用,因为根据定义,查询的输出行已经是唯一的。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')