简体   繁体   中英

SQL Query Confusion

Employee(person-name, age, street, city)
Work(person-name, company-name, salary)
Company(company-name, city)
Manage(person-name, manager-name)

What I need to do is create a SQL query for the following : Write a query in SQL to nd the names of such companies that all of their employees have salaries higher than $100000

This is what I got :

Select company-name From Company Where (Select salary From Work Where Salary > 100000)

I'm kind of confused why this is wrong. I'm still a beginner so if someone could guide me, that be really appreciated

This is a bit confusing, because one way in SQL is a double negative:

Select c.companyname 
From Company c
Where not exists (select 1
                  from Work w
                  where w.companyname = c.companyname and w.salary < 100000
                 );

Here you have to join two tables to get this result, but if you want to use the sub query you have to select the column that is same or a refrence column

ie

Select company-name 
From Company
Where company-name in  (Select company-name From Work Where Salary > 100000)

Query with join.

select 
    company-name,person-name,salary
from 
    Company c  join  work w using(company-name)
where 
    salary > 100000;
select c.company-name,w.salary [higher than $100000]
from Company as c
inner join Work as w
on c.company-name = w.company-name
where w.salary > $100000;

I think you are trying to do this in your query:

Select company-name 
 From Company
 Where company-name in (Select company-name
        From Work
        Where Salary > 100000)

From what I can see; it is pointless using the IN clause here. You may as well do this:

Select company-name
            From Work
            Where Salary > 100000

In reality you would need the IN clause or alternatively an INNER JOIN to get the company name as the company name would be stored in the company table and the tables (company and work) would be joined using keys (primary keys and foreign keys) and therefore you would get the company name from the Company table.

The problem with the query in the question is that its syntax is not valid. You can't say

SELECT something
FROM some_table
WHERE (another query)

That's just not valid. The elements in the WHERE clause must be a series of logical conditions, not a query.

I'd do something like the following:

WITH COMPANY_MIN_SALARIES AS
  (SELECT w.COMPANY_NAME, MIN(w.SALARY) AS MIN_SALARY
     FROM WORK w
     GROUP BY w.COMPANY_NAME)
SELECT ms.COMPANY_NAME
  FROM COMPANY_MIN_SALARIES ms
  WHERE ms.MIN_SALARY > 100000;

Best of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM