我有一个日历表:
CREATE TABLE [dbo].[FIN_CalendarTable](
[id] [int] IDENTITY(1,1) NOT NULL,
[date] [datetime] NOT NULL,
[fiscalStart] [datetime] NULL,
[fiscalEnd] [datetime] NULL,
[isHoliday] [int] NOT NULL,
[isWorkday] [int] NOT NULL
CONSTRAINT [PK_FIN_CalendarTable] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
我想计算财政年度每周的工作日数量。我有以下查询,它返回会计周和会计期间的每个工作日(250 条记录):
SELECT dbo.CalendarTable.fiscalStart
, dbo.CalendarTable.fiscalEnd
, COUNT(*)
, dbo.CalendarTable.monthOfYearName
, dbo.CalendarTable.monthStart
, dbo.CalendarTable.monthEnd
, DATEDIFF(DAY, dbo.CalendarTable.fiscalStart, [date]) / 7 + 1 WeekOfFiscalYear
FROM dbo.CalendarTable
WHERE dbo.CalendarTable.isHoliday=0
AND dbo.CalendarTable.isWorkday=1
AND ( dbo.CalendarTable.date >= CONVERT(DATETIME,'01/07/2012',103)
AND dbo.CalendarTable.date <= CONVERT(DATETIME,'30/06/2013',103) )
GROUP BY dbo.CalendarTable.fiscalStart
, dbo.CalendarTable.fiscalEnd
, dbo.CalendarTable.monthOfYearName
, dbo.CalendarTable.monthStart
, dbo.CalendarTable.monthEnd
, [dbo].[CalendarTable].[date]
我意识到这是因为 group by 包含 [dbo].[CalendarTable].[date] 列。是否有更好的方法来构建此查询,以便在每个会计周中返回 52 条(或适当时为 53 条)记录以及总计工作日?
我可能可以在应用程序中实现聚合,但如果可能的话,我希望获得一组更好的结果。