Suponemos que estos son los datos:
Código SQL:
Ver originalCREATE TABLE #T(Consultor CHAR(1),
Comprador CHAR(3),
Fecha DateTime);
CREATE Clustered INDEX Idx_#T ON #T(Consultor,Comprador,Fecha);
GO
INSERT
INTO #T
VALUES ('A','A1','20140101'), --buena
('A','A1','20140215'),
('A','A2','20140101'), --mala
('A','A2','20140115'),
('A','A3','20140101'), --buena
('B','B1','20140101'), --mala
('B','B1','20140110'),
('B','B2','20140101'), --mala
('B','B2','20140101'),
('C','C1','20140101'), --buena
('C','C1','20140215'),
('C','C1','20140401');
El resumen e este caso:
Código SQL:
Ver originalWITH T1 AS
(SELECT ROW_NUMBER() OVER (Partition BY Consultor,Comprador ORDER BY Fecha) N,
*
FROM #T),
T2 AS
(SELECT Consultor,
Comprador,
CASE WHEN COUNT(*)= 2 THEN DateDiff(DAY,MIN(Fecha),MAX(Fecha)) ELSE NULL END Plazo
FROM T1
WHERE N IN (1,2)
GROUP BY Consultor,
Comprador)
SELECT Consultor,
COUNT(*) Total,
SUM(CASE WHEN Plazo<31 THEN 0 ELSE 1 END) Buenas,
SUM(CASE WHEN Plazo<31 THEN 1 ELSE 0 END) Malas
FROM T2
GROUP BY Consultor;