1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

年度を計算

Last updated at Posted at 2025-03-28

はじめに

日付に関する小ネタを紹介します。
自分の中では当たり前に使っていましたが、職場での反応が良かったので記事にしようと思います。

年度を計算

C#
int fiscalYear;
if (DateTime.Today.Month < 4)
{
    // 1~3月は前年
    fiscalYear = DateTime.Today.Year - 1;
}
else
{
    // 4~12月は当年
    fiscalYear = DateTime.Today.Year;
}

日付の3ヶ月前の年を取れば年度が取得できます。

C#
int fiscalYear = DateTime.Today.AddMonths(-3).Year;

条件分岐がなく、シンプルにできました。

2つの期間が重なるデータ

2つの期間は以下の6パターンに分けられます。
image.png

期間が重なるデータなので、抽出したいデータは②③④⑤です。

SQL
SELECT *
  FROM table_1
 INNER JOIN table_2
         ON table_1.id = table_2.id
 WHERE (table_1.startDate >= table_2.startDate
        AND
        table_1.startDate <= table_2.endDate) -- 2,3
    OR (table_2.startDate >= table_1.startDate
        AND
        table_2.startDate <= table_1.endDate) -- 4,5

ちょっと分かりづらいです。

ここで期間は必ず6パターンに収まるので、①⑥以外を求めると②③④⑤になります。

②または③または④または⑤
 WHERE (table_1.startDate >= table_2.startDate
        AND
        table_1.startDate <= table_2.endDate)
    OR (table_2.startDate >= table_1.startDate
        AND
        table_2.startDate <= table_1.endDate)

「① または ②」以外
 WHERE NOT (table_1.startDate > table_2.endDate
            OR
            table_2.startDate > table_1.endDate)

①以外 かつ ②以外
 WHERE NOT table_1.startDate > table_2.endDate
   AND NOT table_2.startDate > table_1.endDate

つまり、こうなります。

SQL
SELECT *
  FROM table_1
 INNER JOIN table_2
         ON table_1.id = table_2.id
 WHERE table_1.startDate <= table_2.endDate
   AND table_2.startDate <= table_1.endDate
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?