subqueries refatorar usando GROUP BY / tendo?
-
21-08-2019 - |
Pergunta
Estou construindo uma consulta MySQL para determinar quantos itens de cada uma das várias categorias aparecem em um determinado intervalo de datas. Minha primeira tentativa ficou assim:
select Title,
(select count(*) from entries where CategoryID=1
and Date >= @StartDate and Date <= @EndDate) as Cat1,
(select count(*) from entries where CategoryID=2
and Date >= @StartDate and Date <= @EndDate) as Cat2,
(select count(*) from entries where CategoryID is null
and Date >= @StartDate and Date <= @EndDate) as UnkownCategory
from entries
where Date >= @StartDate and Date <= @EndDate
A tabela é muito grande e eu gostaria de refazer a consulta para acelerá-lo, mas eu não sei como - isso pode ser reescrito usando GROUP BY / TENDO declarações ou há outra maneira que eu estou perdendo?
Editar : Sample conjunto de resultados - algo como isto:
Title | Category 1 Total | Category 2 Total | Unknown Category Total
ABC 1 3 0
DEF 2 7 2
Solução
select Title, SUM(CategoryID=1) as Cat1, SUM(categoryID=2) as Cat2,
SUM(categoryID IS NULL) as UnknownCategory
FROM entries
WHERE Date BETWEEN @StartDate AND @EndDate
GROUP BY Title
Você pode furar expressões na soma () funções:. A verdade é igual a 1, o falso é igual a 0. Também eu usei o operador BETWEEN que é um pouco mais rápido
Uma alternativa que voltaria um layout resultado diferente, mas é um pouco conceitualmente mais simples:
select Title, CategoryID, count(*)
from entries
WHERE Date BETWEEN @StartDate AND @EndDate
group by Title, CategoryID
Outras dicas
Como sobre agrupamento por categoria ID, em seguida, usando o ter comunicado para filtrar categorias específicas, como:
select CategoryID, count(*)
from entries
where Date >= @StartDate AND Date <= @EndDate
group by CategoryID
having CategoryID = 1 or CategoryID = 2 or CategoryID is null
Se houver vários títulos por categoria, você poderia grupo por ambos os campos:
select Title, CategoryID, count(*)
from entries
where Date >= @StartDate AND Date <= @EndDate
group by Title, CategoryID
having CategoryID = 1 or CategoryID = 2 or CategoryID is null
Select COUNT(*), sTitle, CategoryID FROM entries
WHERE Date >= @StartDate and Date <= @EndDate
GROUP BY CategoryID, sTitle