Skip to content

Instantly share code, notes, and snippets.

@smichaelsen
Created October 1, 2015 12:47
Show Gist options
  • Save smichaelsen/173332bfdc15c5f11a2a to your computer and use it in GitHub Desktop.
Save smichaelsen/173332bfdc15c5f11a2a to your computer and use it in GitHub Desktop.
MySQL Kata #1
+------+-------+
| type | value |
+------+-------+
| a    | 2     |
+------+-------+
| a    | 5     |
+------+-------+
| c    | 1     |
+------+-------+
| b    | 8     |
+------+-------+
| c    | 3     |
+------+-------+
| a    | 2     |
+------+-------+
| b    | 4     |
+------+-------+
| a    | 2     |
+------+-------+

Quest: Return the sum of all atype records as sum_a and the sum of all b type records in sum_b in one query.

CREATE TABLE `kata1` (
`type` varchar(11) NOT NULL DEFAULT '',
`value` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `kata1` (`type`, `value`)
VALUES
('a',2),
('a',5),
('c',1),
('b',8),
('c',3),
('a',2),
('b',4),
('a',2);
@etobi
Copy link

etobi commented Oct 1, 2015

I guess there might be a more performant solution. However this fulfills all the conditions.

https://gist.github.com/etobi/01bc825e1499ccc49e02

@fjacobi
Copy link

fjacobi commented Oct 2, 2015

It uses more than one query.
After wasting a lot of time with GROUP BY I denied myself the pleasure of solving this alone.
Don't think I'd figured that one out by myself.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment