I have to come and ask this because I’m already angry and crying and everything, because this really kills me. I hate SQL. But it has to be done. Website uses SQL.
I have these tables (shortened to the necessessary and not real SQL):
CREATE TABLE deliverer(d_id INT PRIMARY KEY, name VARCHAR(80));
CREATE TABLE article(a_id INT PRIMATY KEY, brand VARCHAR(80));
CREATE TABLE delivers(d_id FOREIGN KEY(deliverer), a_id FOREIGN KEY(article));
I need, for each brand those deliverers that deliver the most articles. I’ve come as far as this, after only two hours of mind twisting:
SELECT brand, MAX(cnt)
FROM
(SELECT COUNT(a.a_id) AS cnt, a.brand, d.d_id, d.name
FROM derliverer d, delivers l, article a
WHERE a.a_id = l.a_id AND l.d_id = d.d_id
GROUP BY a.brand, d.d_id, d.name)
GROUP BY brand;
What I really, really, really don’t get about SQL is why it does not let me GROUP BY brand and SELECT the d.name, d.d_id. It really makes no sense.
Please help me before I jump out of the window.
Because if you do, the count will be for each distinct d.name, d.d_id. This is not what you want.
You definitely want to read some tutorials on how a group by works.
In this case you need something like: