2011-08-19 43 views
0

我有一個SQL查詢,我無法以我想要的方式顯示。基本上,我們已經有了一張充滿交易的表格,我希望從今年2月份開始購買一筆交易(特定類型的交易)。下面是該查詢:顯示SELECT查詢結果 - 從相同的表 - 並排

select sum(amount) as "2011" from transactions 
where transaction_type = 'registration' 
and date_entered > '2011-02-01' 
and date_entered < GetDate() 

現在,我也想看看這些相同的交易的總和,但前一年:

select sum(amount) as "2010" from transactions 
where transaction_type = 'registration' 
and date_entered > '2010-02-01' 
and date_entered < DateAdd(yy, -1, GetDate()) 

似乎我無法弄清楚是如何並行獲得這些總和。我試過UNION all,但這些顯示在單獨的行中,而不是列。

select sum(amount) as "2011" from transactions 
where transaction_type = 'registration' 
and date_entered > '2011-02-01' 
and date_entered < GetDate() 
UNION all 
select sum(amount) as "2010" from transactions 
where transaction_type = 'registration' 
and date_entered > '2010-02-01' 
and date_entered < DateAdd(yy, -1, GetDate()) 

我也讀到這裏對堆棧溢出是PIVOT可能是一種選擇,但我還沒有看到,我可以操控/調整上面查詢的例子。

有關我如何並行獲取此數據的任何建議?我確信我忽略了一些簡單的東西。

非常感謝!

+0

你永遠只能去本年度來比較以前還是有這個方程的變量?如果沒有其他變量,那麼我不明白爲什麼你需要使用PIVOT,波希米亞的例子就足夠了。 – deutschZuid

回答

0

快速和醜陋的解決方案是這樣的:

SELECT (
select sum(amount) as "2011" from transactions 
where transaction_type = 'registration' 
and date_entered > '2011-02-01' 
and date_entered < GetDate()) as '2011', 
(select sum(amount) as "2010" from transactions 
where transaction_type = 'registration' 
and date_entered > '2010-02-01' 
and date_entered < DateAdd(yy, -1, GetDate())) as '2010' 

您可以使用此爲一次性查詢,但肯定是我想要的東西添加到生產系統。

有關PIVOT檢查一個很好的例子,這一個:http://rajaramtechtalk.wordpress.com/2008/05/13/how-to-use-pivot-in-sql-2005/

你的問題是,你是從2月開始,因此使用DATEPART一年你不會工作,你可能需要使用一個月,他們做了一些工作結果。

1

你想要一個「數據透視表」,它基本上是一個計算形式sum(test * amount)
下面是如何做一個支點,你的情況:

select 
    sum(case when date_entered between '2011-02-01' and < GetDate() then amount else 0 end) as "2011", 
    sum(case when date_entered between '2010-02-01' and DateAdd(yy, -1, GetDate() then amount else 0 end) as "2010" 
from transactions 
where transaction_type = 'registration';