【问题标题】:Displaying SELECT Query Results - from Same Table - Side by Side并排显示 SELECT 查询结果 - 来自同一张表
【发布时间】: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


【解决方案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';

【讨论】:

    【解决方案2】:

    快速而丑陋的解决方案是这样的:

    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 年份对您不起作用,您可能必须使用月份,并且他们会对结果进行一些处理。

    【讨论】:

      猜你喜欢
      • 2019-04-20
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多