简体   繁体   English

如何获得每月和年初至今的总计(SQL查询)

[英]How do I get the totals for each month and YTD (SQL query)

I need to take to get the total of all the months pmts each month for each company then get the full "total" for the months into years to date "YTD" This is the table I have of the records. 我需要获取每个公司每个月所有pmts的总数,然后获取到目前为止的年份中截至“ YTD”为止的月份的完整“总计”。这是我拥有的表。 And the codec right under it. 然后是编解码器。

2014 Total Production 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

and

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

Assuming SQL Server (based on the syntax), you can do what you want as: 假设使用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;

If you have more than one group by column and you want just one summary, then look into GROUPING SETS . 如果group by列有一个以上的group by并且只需要一个摘要,请查看GROUPING SETS

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM