组UNION-ised结果,同时不丢失列

时间:2014-03-12 13:14:43

标签: sql sql-server group-by union

我遇到以下问题:

我有以下结果集:

| ForecastAmount | AmountAchieved | MonthID | EmployeeID | ForecastWeek | WeekAchieved |
|       NULL     |     51.541     |   132   |      7     |      NULL    |    2014-09   |
|       NULL     |    101.223     |   132   |     31     |      NULL    |    2014-09   |
|     220.000    |      NULL      |   132   |      7     |    2014-05   |      NULL    |
|     214.5665   |      NULL      |   132   |     31     |    2014-05   |      NULL    |

我通过类似于以下查询的方式做了什么:

       SELECT SUM(Amount) as ForecastAmount
             ,NULL as AmountAchieved
             ,MonthID
             ,ForecastWeek
             ,NULL as WeekAchieved
             ,EmployeeID
       FROM (Query 1)
   UNION
      SELECT NULL as ForecastAmount
            ,Sum(AmountAchieved)
            ,MonthID
            ,NULL as ForecastWeek
            ,WeekAchieved
            ,EmployeeID
      FROM (Query 2)
Group by MonthID,ForecastWeek,WeekAchieved,EmployeeID

现在我想要的是以下内容:

| ForecastAmount | AmountAchieved | MonthID | EmployeeID | ForecastWeek | WeekAchieved |
|     220.000    |     51.541     |   132   |      7     |    2014-05   |    2014-09   |
|     214.5665   |    101.223     |   132   |     31     |    2014-05   |    2014-09   |

基本上我想要的是由 EmployeeID Month 分组的相同结果集,而 ForecastWeek WeekAchieved 不会被遗漏,而是落入正确的地方。

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你想做一个简单的聚合:

SELECT SUM(Amount) as ForecastAmount,
       SUM(AmountAchieved) as AmountAchieved,
       MonthID,
       MAX(ForecastWeek) as ForecastWeek,
       MAX(WeekAchieved) as WeekAchieved,
       EmployeeID
FROM (Query 1) q
GROUP BY MonthID, EmployeeID;