简体   繁体   中英

SQL: Joins with two basic tables

Got two SQL tables, structure and values are mentioned below.

Table 1: Employee

    CREATE TABLE `employee` (
  `EmpId` int(11) NOT NULL,
  `EmpName` varchar(100) NOT NULL,
  `DeptId` int(11) NOT NULL,
  `Jod` date NOT NULL,
  `Salary` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;



INSERT INTO `employee` (`EmpId`, `EmpName`, `DeptId`, `Jod`, `Salary`) VALUES
(1, 'ABCD', 1, '2015-02-23', 50000),
(2, 'EFGH', 1, '2016-04-11', 40000),
(3, 'HIJK', 2, '2016-05-22', 35000),
(4, 'LMNO', 3, '2016-05-22', 30000),
(5, 'PQRS', 3, '2016-06-03', 30000);

Table 2: Department

CREATE TABLE `dept` (
  `DeptId` int(11) DEFAULT NULL,
  `DeptName` varchar(100) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;



INSERT INTO `dept` (`DeptId`, `DeptName`) VALUES
(1, 'Sales'),
(2, 'Account'),
(3, 'Support');

Now out of these two I need to query to print every Department name and the count of employees in that department.

And I have tried with the following query

SELECT DISTINCT(dept.DeptName),COUNT(employee.EmpId) FROM dept JOIN employee on dept.DeptId = employee.DeptId

which yields the result

DeptName  COUNT(employee.EmpId)
Sales      5

But Actual result what i need is

DeptName  COUNT(employee.EmpId)
Sales      2
Accounts   1
Support    2

How to achieve it, Any help appreciated.

You want GROUP BY :

SELECT d.DeptName, COUNT(e.EmpId)
FROM dept d JOIN
     employee e
     ON e.DeptId = d.DeptId
GROUP BY d.DeptName;

I'm not sure what your thought-process is on using DISTINCT . First, it applies to all the columns being selected; it is not a function. The parentheses are immaterial.

Second, you are using an aggregation function ( COUNT() ) and thought should automatically point you in the direction of GROUP BY .

Here is a db<>fiddle.

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