はじめに
日付に関する小ネタを紹介します。
自分の中では当たり前に使っていましたが、職場での反応が良かったので記事にしようと思います。
年度を計算
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つの期間が重なるデータ
期間が重なるデータなので、抽出したいデータは②③④⑤です。
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