[英]How do I get the totals for each month and YTD (SQL query)
我需要獲取每個公司每個月所有pmts的總數,然后獲取到目前為止的年份中截至“ 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
假設使用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
列有一個以上的group by
並且只需要一個摘要,請查看GROUPING SETS
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.