如何获取每月的总计和YTD(SQL查询)

时间:2014-05-21 15:25:19

标签: sql sql-server totals

我需要为每家公司获取每个月的所有月份总数,然后获得全部"总计"到今年为止的几个月" YTD"这是我记录的表格。而编解码就在它下面。

2014年总产量

    Jan-14  Feb-14  Mar-14  Apr-14  2014 YTD
Alpha corp  10  24  18  10  62
zeen corp   10  14  16  21  61
open corp   20  6   18  12  56
geez corp   15  5   14  8   42
mine corp   5   7   16  12  40
little corp 10  5   7   10  32
Vize corp   4   5   20  2   31
deng corp   5   9   8   9   31
nine corp   7   5   8   10  30
wash corp   5   8   7   10  30
hass corp   6   9   8   7   30
2014 YTD    77  97  144 222 445

Declare @year int
Set @year = 2014

select 
   a.first_name, a.last_name,
   Count(case when Month(b.funded_date) = 1 Then 1 else Null End) Janurary, 
   Count(case when Month(b.funded_date) = 2 Then 1 else Null End) Feburary ,
   Count(case when Month(b.funded_date) = 3 Then 1 else Null End) March,
   Count(case when Month(b.funded_date) = 4 Then 1 else Null End) April
from 
   tContact a 
Inner join 
   tContract b On a.contact_id = b.contract_id
Group by 
   first_name, last_name

1 个答案:

答案 0 :(得分:0)

假设SQL Server(基于语法),您可以执行以下操作:

select a.first_name + a.last_name,
       sum(case when Month(b.funded_date) = 1 Then 1 else 0 End) Janurary, 
       sum(case when Month(b.funded_date) = 2 Then 1 else 0 End) Feburary ,
       sum(case when Month(b.funded_date) = 3 Then 1 else 0 End) March,
       sum(case when Month(b.funded_date) = 4 Then 1 else 0 End) April,
       sum(case when Month(b.funded_date) <= 4 then 1 else 0 end) as YTD
from tContact a Inner join
     tContract b
     On a.contact_id = b.contract_id
Group by first_name + last_name with rollup;

如果您有多个group by列,并且只需要一个摘要,请查看GROUPING SETS