简体   繁体   中英

Group By and Order By with UNION ALL

I have a stored procedure with the following query:

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)  

I need to do a union all , so I could get sum of results but from TWO tables , and I want the result to be grouped by and ordered by the same way.

This doesn't work:

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) 

I want to order the overall result, and group it by the date.

You could apply the group by and order by after the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM