F
F
fruityiceangel2014-04-30 21:01:17
SQL
fruityiceangel, 2014-04-30 21:01:17

Ms sql, select from a table, subquery - how to do it?

There is a table: EmployesInfo
with columns: emplId, emolName, EmplCar, ChiefId
You need to select only those employees who have an assigned boss, the assigned boss has a car and the boss must have at least 3 dependencies (an employee with emplId is subordinate to the boss) .

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2014-04-30
@Rsa97

SELECT `employer`.* 
    FROM `EmployesInfo` AS `employer`
    RIGHT JOIN `EmployesInfo` AS `chief` ON `employer`.`ChiefId` = `chief`.`emplId`
    RIGHT JOIN (SELECT `ChiefId`, COUNT(`ChiefId`) AS `count` 
                FROM `EmployesInfo`
                GROUP BY `ChiefId`
                HAVING `count` >= 3) AS `sub` ON `employer`.`ChiefId` = `sub`.`ChiefId`
    WHERE `chief`.`EmplCar` IS NOT NULL

M
Mulder_ua, 2014-04-30
@Mulder_ua

I would put cars and chefs in separate tables so that there would be a 3rd form, but in this case it can be done like this:

SELECT emplId
FROM EmployesInfo
WHERE ChiefId IN (
    SELECT emplId
    FROM EmployesInfo
    --Находим шефов
    WHERE emplId IN (
        SELECT ChiefId
        FROM EmployesInfo
        GROUP BY ChiefId
        --Что бы ему подчинялось >= 3 человека
        HAVING count(1) >= 3
        )
      --Уточняем что шеф не нищеброт и у него есть машина
      AND EmplCar IS NOT NULL
    )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question