2011-05-20 77 views
0

我的做法是:SQL程序選擇合併

create procedure "news" 
as 
select newsdate,COUNT(B.id) as total from news B 
where B.newsyear < GETDATE() 
Group by B.newsdate 

select newsdate,COUNT(B.id) as total from news B 
where B.status='WAITING' and B.cancel='1' 
Group by B.newsdate 

結果:

newsdate total 
2011  4 
2010  8 

newsdate total 
2011  2 
2010  3 

如何合併一年總計獲得這個結果集:

newsdate total 
2011  6  {4 + 2} 
2010  11  {8 + 3} 

回答

0

使用簡單或聲明(如果它確實是同一個表):

select newsdate,COUNT(B.id) as total 
from news B 
where B.newsyear < GETDATE() 
    or B.status='WAITING' and B.cancel='1' 
Group by B.newsdate 

,或者使用UNION ALL + Sum聚集(如果它是不同的表):

select newsdate, sum(total) as total from (
    select newsdate,COUNT(B.id) as total from news B where B.newsyear < GETDATE() 
    Group by B.newsdate 
    union all 
    select newsdate,COUNT(B.id) as total from news B where B.status='WAITING' and B.cancel='1' 
    Group by B.newsdate 
) as rows 
group by newsdate 
+0

謝謝工會的所有工作。 – bulent 2011-05-20 13:32:47

1

試試這個:

select newsdate,COUNT(B.id) as total 
from news B 
where (B.newsyear < GETDATE()) 
or (B.status='WAITING' and B.cancel='1') 
Group by B.newsdate