Wednesday, November 27, 2013

GROUP BY clause and table join


CREATE TABLE DBO.EMPLOYEE (
FNAME NVARCHAR(50)
, SNAME NVARCHAR(50)
, DNO INT)

INSERT INTO DBO.EMPLOYEE
SELECT 'JOHN', 'SMITH', 5
INSERT INTO DBO.EMPLOYEE
SELECT 'FRANKLIN', 'WONG', 5
INSERT INTO DBO.EMPLOYEE
SELECT 'JOYCE', 'ENGLISH', 5
INSERT INTO DBO.EMPLOYEE
SELECT 'RAMESH', 'NARAYAN', 5
INSERT INTO DBO.EMPLOYEE
SELECT 'JAMES', 'BORG', 1
INSERT INTO DBO.EMPLOYEE
SELECT 'JENNIFER', 'WALLACE', 4
INSERT INTO DBO.EMPLOYEE
SELECT 'AHMAD', 'JABBAR', 4
INSERT INTO DBO.EMPLOYEE
SELECT 'ALICIA', 'ZELAYA', 4

CREATE TABLE DBO.DEPARTMENT (
DNUMBER INT, DNAME NVARCHAR(50))

INSERT INTO DBO.DEPARTMENT
SELECT 1, 'HEADQUARTERS'
INSERT INTO DBO.DEPARTMENT
SELECT 2, 'DEVELOPMENT'
INSERT INTO DBO.DEPARTMENT
SELECT 3, 'SALES'
INSERT INTO DBO.DEPARTMENT
SELECT 4, 'ADMINISTRATION'
INSERT INTO DBO.DEPARTMENT
SELECT 5, 'RESEARCH'

SELECT DEPARTMENT.DNAME, COUNT(EMPLOYEE.DNO) AS RECORDS
FROM DBO.DEPARTMENT
JOIN EMPLOYEE
ON DEPARTMENT.DNUMBER = EMPLOYEE.DNO
GROUP BY DEPARTMENT.DNAME
HAVING COUNT(EMPLOYEE.DNO) >= 3

No comments:

Post a Comment