mercredi 10 février 2016

Proble with joining two tables on subquery condition

I have 2 tables:

1) et_pics - here information about employees:

  • ob_no, int, key, e.g. 2020
  • c_name, varchar, e.g. Dribbler D.E.
  • e_post, varchar, e.g. Chairman

    SELECT * FROM et_pics:

ob_no | c_name | e_post

2020 | Dribbler D.E. | Chairman

2) et_vacations – here information about vacation is stored:

  • ob_no, int, e.g. 666 e_pic, int, connection to pic.ob_no, e.g. 2020
  • c_name, varchar, e.g. Vacation blah blah
  • e_dateFrom, date, e.g. 2010-08-08 00:00:00.000
  • e_dateTo, date, e.g 2010-08-09 00:00:00.000

    SELECT * FROM et_vacations vac returns

ob_no | e_pic |c_name | e_dateFrom |e_dateTo
| 777 | 2020 |Vacation blah blah |2010-08-08 00:00:00.000 | 2010-08-09 00:00:00.000 |

777 | 2020 |Vacation blah blah |2015-08-08 00:00:00.000 | 2015-08-09 00:00:00.000 |

What I need to do is to connect et_vacations to et_pics with conditions:

  • the could be only one vacation record per person (seems to me max(e_dateTo));
  • vacation record must be >= getDate() or null is displayed.

Can’t understand how to write right subquery – tried in this way, but no luck:

SELECT
    pics.c_name,
    pics.e_post,
vac.e_dateTo
FROM et_pics pics
INNER JOIN et_division div on pics.e_division = div.ob_no
INNER JOIN et_vacations vac on vac.e_pic = pics.ob_no
WHERE
    (pics.e_fireDate IS NULL OR pics.e_fireDate > getDate()) 
    AND vac.e_dateTo IN (
    SELECT MAX(vac.e_pic) from et_vacations vac
    GROUP BY vac.e_pic
    )
    ORDER BY pics.c_name;

Thanks in advance for any help to solve this question.

Aucun commentaire:

Enregistrer un commentaire