patternsqlMinor
Query: All employee with sum of salary > 500
Viewed 0 times
salaryemployeeallwithquery500sum
Problem
In my MYSQL Database COMPANY, I have a Table:
I created using following MySQL's command:
The table having following data:
its insert query:
[QUESTION]
I wants to select first n
following four workers are first low salary employees and having SUM of salary 600. (600 > 500)
I need something like
A suggestion or link to read will be helpful
Worker : mysql> DESC `Worker`;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| SSN | varchar(64) | NO | | NULL | |
| name | varchar(64) | YES | | NULL | |
| salary | int(11) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)I created using following MySQL's command:
CREATE TABLE `Worker` (
`SSN` varchar(64) NOT NULL,
`name` varchar(64) DEFAULT NULL,
`salary` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;The table having following data:
mysql> SELECT * FROM `Worker` ORDER BY salary ASC;
+-----+---------+--------+
| SSN | name | salary |
+-----+---------+--------+
| 6 | TWO | 50 |
| 5 | ONE | 100 |
| 1 | Grijesh | 200 |
| 3 | Sumit | 250 |
| 2 | Rahul | 300 |
| 4 | Harsh | 500 |
| 7 | THREE | 1000 |
+-----+---------+--------+
7 rows in set (0.00 sec)its insert query:
INSERT INTO `Worker`
(SSN, name, salary)
VALUES
("1", "Grijesh", 200),
('2','Rahul',300),
('3','Sumit',250),
('4','Harsh',500),
('5','ONE','100'),
('6','TWO',50),
('7','THREE',1000);[QUESTION]
I wants to select first n
workers (in asc list)those sum of salary is just more than 500 (> 500). for example: following four workers are first low salary employees and having SUM of salary 600. (600 > 500)
| 6 | TWO | 50 |
| 5 | ONE | 100 |
| 1 | Grijesh | 200 |
| 3 | Sumit | 250 |I need something like
SELECT * FROMWorker`WHERE SUM(salary) its something like cost cutting: remove employee those are relatively unimportant A suggestion or link to read will be helpful
Solution
After playing around with this some more, I came up with this query:
This seems to do what you want on this limited data, but could be very slow on large datasets.
SELECT ssn, name, salary FROM (
SELECT ssn, name, salary, (@total:=@total+salary) as total
FROM worker, (select @total:=0) t
ORDER BY salary ASC
) as foo
WHERE (total-salary) <=500This seems to do what you want on this limited data, but could be very slow on large datasets.
Code Snippets
SELECT ssn, name, salary FROM (
SELECT ssn, name, salary, (@total:=@total+salary) as total
FROM worker, (select @total:=0) t
ORDER BY salary ASC
) as foo
WHERE (total-salary) <=500Context
StackExchange Database Administrators Q#33497, answer score: 4
Revisions (0)
No revisions yet.