2015-01-07 113 views
7

我有以下查詢存儲過程:集團通過和ORDER BY與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][email protected] 
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][email protected] 
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][email protected] 
GROUP BY CONVERT(VARCHAR(12),CREATED,102) 
ORDER BY CONVERT(VARCHAR(12),CREATED,102) 

我要訂購的總體結果,並通過日化集團的。

+0

只能訂購工會,不是每一個人查詢的整體效果。 –

+0

@a_horse_with_no_name這正是我想要的。我能夠訂購整體結果,但我不能分組 – HelpASisterOut

+0

您是否嘗試過使用別名子查詢,然後通過alias.field_name進行分組? – chridam

回答

11

您可以在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][email protected] 
     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][email protected]) t 
GROUP BY [date] 
ORDER BY 2 
+0

我當然試過。但是得到了無效的列名'date'。 – HelpASisterOut

+0

可能與別名有關 - 編輯後,應該立即工作。 – Mureinik