Calendar Tableを作成して入力します(これにより、日付の作業がはるかに簡単になります)。の
select C.*, FY.year fiscal_year from Calendar C inner join FiscalYear FY on FY.id = C.id
:あなたが指定した日付の会計年度を必要なとき
create view FiscalYear
as
select
id,
case when month = 11 or month = 12 then year + 1 else year end as [year]
from Calendar
だから、ちょうど次のクエリのようなものを使用します。
その後
create table Calendar
(
id int primary key identity,
[date] datetime,
[day] as datepart(day, [date]) persisted,
[month] as datepart(month, [date]) persisted,
[year] as datepart(year, [date]) persisted,
day_of_year as datepart(dayofyear, [date]) persisted,
[week] as datepart(week, [date]),
day_name as datename(dw, [date]),
is_weekend as case when datepart(dw, [date]) = 7 or datepart(dw, [date]) = 1 then 1 else 0 end,
[quarter] as datepart(quarter, [date]) persisted
--etc...
)
--populate the calendar
declare @date datetime
set @date = '1-1-2000'
while @date <= '12-31-2100'
begin
insert Calendar select @date
set @date = dateadd(day, 1, @date)
end
、FiscalYear
ビューを作成しますもちろん、会計年度は単なる列の計算なので、それをカレンダー表自体の一部にすることもできます。その後、それは単にです:
select * from Calendar
会計期間を含むテーブルを作成します。参加して日付を比較してください。次に、クエリで必要なときに会計期間テーブルを使用することができます。 –
脇に:あなたの 'case'式が' month(a.InvoiceDate) '以外のすべてに文字列値を使用していることが不思議です。 [データ型の優先順位](https://docs.microsoft.com/en-us/sql/t-sql/data-types/data-type-precedence-transact-sql)に基づいて、各 'when'値が変換されます比較前に整数に変換する。 'then'値は文字列のままです。ヒント:適切なソフトウェア(MySQL、Oracle、DB2など)とバージョンの両方でデータベースの質問にタグを付けると便利です。 'sql-server-2014'です。 'tsql'は選択肢を絞り込みますが、データベースは指定しないことに注意してください。 – HABO