dポイントプレゼントキャンペーン実施中!

社員の中で直近の1ヶ月に誕生日を迎える社員を抽出し近い日付から順番に表示したいと思っています。
以前ご教示頂いたコードで出来たのですが、少しおかしい点が見つかりました。

現在では下記のように正常に表示されます。
3月2日  山田
3月15日 菊池
3月22日 田中

しかし、実際に山田の誕生日である当日(3月2日)になると、山田のデータは一番下に表示されてしまいます。
3月15日 菊池
3月22日 田中
3月2日  山田

コードは下記のようになっています。

$stmd = date('m/d');
$endmd = date('m/d', strtotime('+1month'));
$join = $stmd < $endmd ? 'and' : 'or';

$sql="SELECT office.*, (case when date_format(birth, '%m/%d') <= ? then 1 else 0 end) as sw FROM office where date_format(birth, '%m/%d') >= ? " . $join . " date_format(birth, '%m/%d') <= ? order by sw, date_format(birth, '%m/%d')";

これはどのようにすれば当日になっても順番どおりに表示させることが出来るでしょうか?
ご存知の方いらっしゃいましたらご教示ください。
よろしくお願いします。

A 回答 (1件)

>直近の1ヶ月に誕生日を迎える



の定義次第ですね

・今月と誕生月が一緒の場合、今日の日付が誕生日の日付より小さい
・来月と誕生月が一緒の場合、今日の日付が誕生日の日付と同じか大きい

ということでよければ、こんな感じ?
(過去1カ月も取りたいとなるともうちょい工夫が必要)

//元データ
create table office (birth date,name varchar(20));
insert into office values('1960-03-02','山田'),('1970-03-15','菊池'),('1980-03-22','田中');

//今日が2014-02-10の場合
SELECT office.* from office
where month(@d:='2014-02-10')=month(birth) and day(@d)<day(birth)
or month(@d)+1=month(birth) and day(@d)>=day(birth)
order by birth asc;
→山田

//今日が2014-02-28の場合
SELECT office.* from office
where month(@d:='2014-02-10')=month(birth) and day(@d)<day(birth)
or month(@d)+1=month(birth) and day(@d)>=day(birth)
order by birth asc;
→山田、菊池、田中

//今日が2014-03-02の場合
SELECT office.* from office
where month(@d:='2014-02-10')=month(birth) and day(@d)<day(birth)
or month(@d)+1=month(birth) and day(@d)>=day(birth)
order by birth asc;
→菊池、田中

//今日を調整しない
SELECT office.* from office
where month(@d:=curdate())=month(birth) and day(@d)<day(birth)
or month(@d)+1=month(birth) and day(@d)>=day(birth)
order by birth asc;
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!

関連するカテゴリからQ&Aを探す