使用 UNION ALL 分组和排序

Group By and Order By with UNION ALL

我有一个包含以下查询的存储过程:

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

我想对整体结果进行排序,并按日期分组。

您可以在 union all:

之后应用 group byorder by
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