2017-04-16 96 views
0

我有一個「活動」表,一個「客戶」表和一個「customer_activity」表。在「活動」表中,每個活動都有自己的ID和開始,結束年份: 因此,每一行都代表一個活動,第一列是開始年份,第二列是結束年份(也就是說,以下是名稱爲X1的特定客戶的活動)。SQL中的每年累計計數

Start End Act_ID 
    2007 2008 1 
    2007 2008 2 
    2009 2009 3 
    2008 2008 4 
    2008 2011 5 
    2007 2008 6 
    2007 2008 7 
    2006 2007 8 
    2006 2006 9 
    2011 2013 10 
    2011 2013 11 

表「客戶」有客戶ID和客戶名稱。最後, 表「customer_activity」具有客戶ID和活動ID。 我想通過客戶名稱查詢(說與客戶名稱X1),並得到一個表是這樣的:

 Year New Total 
     2006 2  2 
     2007 4  5 
     2008 1  4 
     2009 1  2 
     2010 0  1 
     2011 2  3 
     2012 0  2 
     2013 0  2 

我使用MariaDB的10.1.10。 任何人都可以幫助我嗎?

+0

標記您的問題與您正在使用的數據庫。 –

+0

你已經在那個活動表的腳下開槍自殺了。最好用ID,日期來設置它。然後,可以很簡單地說'按年份(日期)'從表名組中選擇年份(日期),總和(id)'。事實上,您可能必須使用程序填寫缺失的日期。 – SandPiper

+0

一些算法最好在應用程序代碼中完成,而不是SQL。 –

回答

0

已經更換了你的相關的列名,你可以試試這個:

select a.start, count(*) as total, count(c.id) as new 
from (select distinct(start) from activity) a 
     left join activity b 
     on a.start between b.start and b.end 
     left join activity c 
     on b.id=c.id and a.start=c.start 
where b.id in (select customer_activity.id 
      from customer left join customer_activity 
      on customer.id = customer_activity.customer_id 
      where customer.name = "X1") 
group by a.start 
0

如果你有多年的列表,你可以使用join和聚集:

select y.yyyy, 
     sum(case when y.yyyy = ca.start then 1 else 0 end) as news, 
     count(ca.customer_id) as total 
from (select 2007 as yyyy union all select 2008 union all . . . 
     select 2013 
    ) y left join 
    customer_activity ca 
    on y.yyyy between ca.start and ca.end left join 
    customer c 
    on ca.customer_id = c.customer_id and c.name = 'X1' 
group by y.yyyy 
order by y.yyyy; 

最好的辦法產生的年這樣的列表取決於數據庫。

+0

我不想手動輸入年份:'選擇2007年作爲yyyy工會所有...' 有沒有辦法自動做到這一點? –

+0

我也沒有得到你如何在開始和結束年與customer_activity一起加入y。 customer_activity沒有任何年份列。 我錯過了什麼嗎? –