如何编写SQL查询以从1表中获取以下结果?

时间:2016-03-07 13:17:53

标签: sql

如何编写查询以获得以下输出:

enter image description here

主表/源表: enter image description here

1 个答案:

答案 0 :(得分:1)

以下是一种使用union all和聚合的方法:

select weeknumber, sum(opened) as opened, sum(closed) as closed
from ((select OpenWeekNumber as weeknumber, 1 as Opened, 0 as Closed
       from maintable
      ) union all
      (select ClosedWeekNumber as weeknumber, 0 as Opened, 1 as Closed
       from maintable
       where ClosedWeekNumber > 0
      )
     ) t
group by weeknumber
order by weeknumber;