I
I
Ivan Karabadzhak2012-01-22 20:04:49
SQL
Ivan Karabadzhak, 2012-01-22 20:04:49

Question about creating a SQL query

Something I can't think of. Probably earned.
There are two tables: subscriptions and subscribers. There are one-to-many "subscribers(1)-subscriptions(many)" relationships, that is, each subscription record contains a "subscriber code" field. The following is required. Find out the number of subscribers who are subscribed to more than 2 subscriptions.
If it is not clear, write comments, I will try to explain better.

Here is CREATE TABLE for tables. Simplified to the maximum.

CREATE TABLE subscriptions
(
id INT,
subscriber_id INT,
);
CREATE TABLE subscribers
(
id INT,
name VARCHAR(64),
surname VARCHAR(64)
);


Here is the query I tried to build, but it does not display what is needed.
SELECT COUNT(subscribers.id)
FROM subscribers INNER JOIN subscriptions ON subscribers.id = subscriptions.subscribers_id
GROUP BY subscribers.id
HAVING COUNT(subscriptions.id) > 2;

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
m08pvv, 2012-01-22
@m08pvv

HAVING count(tra-ta-ta) > 2 is fine?

U
UseRifle, 2012-01-22
@UseRifle

SELECT COUNT(*) FROM
(SELECT subscribers.id
FROM subscribers INNER JOIN subscriptions ON subscribers.id = subscriptions.subscribers_id
GROUP BY subscribers.id
HAVING COUNT(subscriptions.id) > 2) AS counts;

L
lashtal, 2012-01-22
@lashtal

why JOIN???
SELECT COUNT(*) FROM
(
SELECT COUNT(*) cnt FROM subscriptions
GROUP BY subscriber_id
HAVING cnt > 2
) t;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question