【发布时间】:2011-08-19 11:50:47
【问题描述】:
我有一个 SQL 查询,但无法按我想要的方式显示。基本上,我们有一张满是交易的桌子,我想得到一笔从今年 2 月到现在购买的(特定类型的交易)。这是查询:
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())
我在 Stack Overflow 上也读到过 PIVOT 可能是一个选项,但我还没有看到可以针对上述查询进行操作/调整的示例。
关于如何并排获取这些数据有什么建议吗?我确定我忽略了一些简单的事情。
非常感谢!
【问题讨论】:
-
您是否只会将当前年份与前一年进行比较,还是在这个等式中存在变量?如果没有其他变量,那么我不明白你为什么需要使用 PIVOT,波西米亚的例子就足够了。
标签: sql sql-server tsql