2011-08-19 67 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';