SQL中的查询问题

时间:2019-06-04 12:41:23

标签: sql sql-server

我对SQL有以下不便之处。
我必须列出在2018年每个月中复制超过3次的内容,在2019年之后的几个月中复制少于2次的内容。

其结构如下:

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)
)

我创建了以下视图以列出全年的内容,复制品和月份,但事实是我不知道如何过滤每个月复制品超过3件的内容。

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

1 个答案:

答案 0 :(得分:1)

您可以使用条件聚合-但可以使用两个级别。一个按内容和月份,另一个按内容:

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;