1

如何添加每个结果的总和,以便最终结果会给我一个如下表?

日期 | 总和1 | 总和2
1108 | 总和1 | 总和2
等等
DECLARE @StartDate      int
DECLARE @EndDate  int

SET         @StartDate  = XXXXXX
SET         @EndDate    = XXXXXX

SELECT                  ODATE,
                        SUM(CASE WHEN [COLUMN1] IN (X,X) THEN 1 ELSE 0 END)+ SUM(CASE WHEN [COLUMN3] IN (X) THEN 1 ELSE 0 END) AS SUM1,
                      SUM(CASE WHEN [COLUMN2] IN (X,X) THEN 1 ELSE 0 END) AS SUM2


FROM              [Db1]..
WHERE             ODATE Between @StartDate And @EndDate

UNION ALL
SELECT                  ODATE,
                        SUM(CASE WHEN [COLUMN1] IN (X,X) THEN 1 ELSE 0 END)+ SUM(CASE WHEN [COLUMN3] IN (X) THEN 1 ELSE 0 END) AS SUM1,
                      SUM(CASE WHEN [COLUMN2] IN (X,X) THEN 1 ELSE 0 END) AS SUM2        

FROM              [Db2]..
WHERE             ODATE Between @StartDate And @EndDate

UNION ALL
SELECT                  ODATE,
                        SUM(CASE WHEN [COLUMN1] IN (X,X) THEN 1 ELSE 0 END)+ SUM(CASE WHEN [COLUMN3] IN (X) THEN 1 ELSE 0 END) AS SUM1,
                      SUM(CASE WHEN [COLUMN2] IN (X,X) THEN 1 ELSE 0 END) AS SUM2        

FROM              [Db3]..
WHERE             ODATE Between @StartDate And @EndDate
4

1 回答 1

1

包装您的选择,并在其上运行 GROUP BY

DECLARE @StartDate      int
DECLARE @EndDate  int

SET         @StartDate  = XXXXXX
SET         @EndDate    = XXXXXX

SELECT ODATE, SUM(SUM1) Sum1, SUM(SUM2) Sum2
(
  ... your big select ...
) X
GROUP BY ODATE;
于 2012-11-08T22:06:04.387 回答