简体   繁体   中英

How to join two or more tables without a 'common column' in sql

Here is my question from a homework assignment from class that has been giving me some trouble.

Display the month in which more than 5 employees joined in any department located in Syndey.

PS: I apologize for the caps. My teacher instructed me to create the tables like that.

Table locations:

LOCATION_ID    NOT NULL NUMBER(4)    
STREET_ADDRESS          VARCHAR2(40) 
POSTAL_CODE             VARCHAR2(12) 
CITY           NOT NULL VARCHAR2(30) 
STATE_PROVINCE          VARCHAR2(25) 
COUNTRY_ID              CHAR(2)

Table jobs:

JOB_ID     NOT NULL VARCHAR2(10) 
JOB_TITLE  NOT NULL VARCHAR2(35) 
MIN_SALARY          NUMBER(6)    
MAX_SALARY          NUMBER(6) 

Job_history:

JOB_ID     NOT NULL VARCHAR2(10) 
JOB_TITLE  NOT NULL VARCHAR2(35) 
MIN_SALARY          NUMBER(6)    
MAX_SALARY          NUMBER(6) 

Table employees:

EMPLOYEE_ID    NOT NULL NUMBER(6)    
FIRST_NAME              VARCHAR2(20) 
LAST_NAME      NOT NULL VARCHAR2(25) 
EMAIL          NOT NULL VARCHAR2(25) 
PHONE_NUMBER            VARCHAR2(20) 
HIRE_DATE      NOT NULL DATE         
JOB_ID         NOT NULL VARCHAR2(10) 
SALARY                  NUMBER(8,2)  
COMMISSION_PCT          NUMBER(2,2)  
MANAGER_ID              NUMBER(6)    
DEPARTMENT_ID           NUMBER(4)    

Table Departments:

DEPARTMENT_ID   NOT NULL NUMBER(4)    
DEPARTMENT_NAME NOT NULL VARCHAR2(30) 
MANAGER_ID               NUMBER(6)    
LOCATION_ID              NUMBER(4)    

First of all, please don't be apologetic about using caps in SQL scripts. Your teacher is teaching you correct guidelines. It is actually a recommended way (the clean-code way) to write your SQL scripts in capital letters especially SQL keywords and data types for better readability. If you want to keep even your column names in capital then that is your choice.

Well here is your query to get the desired output. You have not mentioned the database you are currently targeting. I've written my query targeting Microsoft SQL Server database.

SELECT HiredMonth,COUNT(HiredMonth)
FROM
(
SELECT DATENAME(MONTH,E.HIRE_DATE) AS HiredMonth
FROM Employees E
INNER JOIN Departments D ON E.DEPARTMENT_ID = D.DEPARTMENT_ID
INNER JOIN Locations L ON D.LOCATION_ID = L.LOCATION_ID
WHERE CITY = 'Sydney') AS P
Group BY P.HiredMonth

PS If you are targeting some other database then few built-in functions used in my query like DATENAME might have to be changed accordingly to make this query compilable in other database.

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