web-dev-qa-db-fra.com

Regroupez et triez avec UNION ALL

J'ai une procédure stockée avec la requête suivante:

SELECT (sum(addition)) AS [COUNT], 
MAX(CONVERT(VARCHAR(12),CREATED,102)) as [date]
FROM [TABLE_ONE]
WHERE convert(VARCHAR(12),CREATED,102) BETWEEN CONVERT(date,@startdate) AND CONVERT(date,@enddate)
AND [ServiceID]=@serid
GROUP BY CONVERT(VARCHAR(12),CREATED,102) 
ORDER BY  CONVERT(VARCHAR(12),CREATED,102)  

Je dois faire un union all, donc je pourrais obtenir la somme des résultats mais à partir de DEUX tables, et je veux que le résultat soit groupé et ordonné de la même manière.

Cela ne fonctionne pas:

SELECT (sum(addition)) AS [COUNT], 
MAX(CONVERT(VARCHAR(12),CREATED,102)) as [date]
FROM [TABLE_ONE]
WHERE convert(VARCHAR(12),CREATED,102) BETWEEN CONVERT(date,@startdate) AND CONVERT(date,@enddate)
AND [ServiceID]=@serid
GROUP BY CONVERT(VARCHAR(12),CREATED,102) 
ORDER BY  CONVERT(VARCHAR(12),CREATED,102)  

UNION ALL

SELECT (sum(addition)) AS [COUNT], 
MAX(CONVERT(VARCHAR(12),CREATED,102)) as [date]
FROM [TABLE_TWO]
WHERE convert(VARCHAR(12),CREATED,102) BETWEEN CONVERT(date,@startdate) AND CONVERT(date,@enddate)
AND [ServiceID]=@serid
GROUP BY CONVERT(VARCHAR(12),CREATED,102) 
ORDER BY  CONVERT(VARCHAR(12),CREATED,102) 

Je veux commander le résultat global et le regrouper par date.

11
HelpASisterOut

Vous pouvez appliquer le group by et order by après le union all:

SELECT  (SUM(addition)) AS [COUNT], MAX([date]) AS [max_date]
FROM    (SELECT addition, CONVERT(VARCHAR(12),CREATED,102)) as [date]
         FROM   [TABLE_ONE]
         WHERE  CONVERT(VARCHAR(12),CREATED,102) 
                    BETWEEN CONVERT(date,@startdate) AND 
                            CONVERT(date,@enddate)
                AND [ServiceID]=@serid 
         UNION ALL
         SELECT addition, (CONVERT(VARCHAR(12),CREATED,102)) as [date]
         FROM   [TABLE_TWO]
         WHERE  CONVERT(VARCHAR(12),CREATED,102) 
                    BETWEEN CONVERT(date,@startdate) AND 
                            CONVERT(date,@enddate)
                AND [ServiceID]=@serid) t
GROUP BY [date]
ORDER BY 2
17
Mureinik