0

I have the following inconvenience with SQL.
I have to list the contents reproduced more than 3 times in each month of 2018 and less than 2 in the months that go of the 2019.

The structure for that is the following:

CREATE TABLE content (
    content INT NOT NULL,
    CONSTRAINT PK_Codcontent PRIMARY KEY(Codcontent) 
)

CREATE TABLE Reproduced (
    Coduser INT NOT NULL,
    Codcontent INT NOT NULL,
    CONSTRAINT PK_Coduser PRIMARY KEY(Coduser, Codcontent),
    CONSTRAINT FK_Codusr FOREIGN KEY(Coduser) REFERENCES Perfil(Codpuser),
    CONSTRAINT FK_Codcont FOREIGN KEY(Codcontent) REFERENCES Contenido(Codcontent)
)

I have created the following view to list the contents, reproductions and months of the whole year, but the thing is that I do not know how to filter those with more than 3 reproductions for each month.

CREATE VIEW TODOSLOSMESES2018
AS
SELECT
      R.Codcontenido
     , count(*)Reproducciones
     , count(Distinct Month(R.fecha)) as 'Meses'
FROM (
       SELECT * 
       FROM Reproduce 
       WHERE fecha>='20180101' AND fecha<='20181231')R
group by Codcontenido
HAVING count(Distinct Month(R.fecha))=12
3
  • You would need to add the Month in the Group by and change the Having to Count(*) Reproducciones > 3 Commented Jun 4, 2019 at 12:49
  • so you only want a list of reproduced's when all 12 months have more than 3 in them or just 3? I would suggest breaking it down into steps. First get a list of reproductions wtih their counts by month. Then figure out how to ensure all 12 months have at least 3. Commented Jun 4, 2019 at 12:50
  • Yes, the point is that I can not think of how. Commented Jun 4, 2019 at 12:55

1 Answer 1

1

You can use conditional aggregation -- but two levels. One by content and month and the other by content:

select codcontent
from (select codcontent, year(fecha) as yr, month(fecha) as mon, count(*) as cnt
      from reproduced r
      group by codcentent, year(fecha), month(fecha)
     ) r
group by codcontent
having sum(case when year = 2018 then 1 else 0 end) = 12 and  -- all months
       min(case when year = 2018 then cnt end) >= 3 and
       max(case when year = 2019 then cnt else 0 end) < 3;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.