【问题标题】:Include Summation Row with Group By Clause在 Group By 子句中包含求和行
【发布时间】:2013-03-15 15:57:18
【问题描述】:

查询:

SELECT aType, SUM(Earnings - Expenses) "Rev"
FROM aTable
GROUP BY aType
ORDER BY aType ASC

结果:

| aType | Rev   |
| ----- | ----- |
| A     | 20    |
| B     | 150   |
| C     | 250   |

问题: 是否可以在我的初始查询中使用 Sybase 语法在底部显示摘要行,如下所示,还是必须完全是一个单独的查询?

| aType | Rev   |
| ----- | ----- |
| A     | 20    |
| B     | 150   |
| C     | 250   |
=================
| All   | 320   |

我无法从 SQL 获取 ROLLUP 函数以成功转换到 Sybase,但我不确定是否有其他方法可以做到这一点,如果有的话。

谢谢!

【问题讨论】:

  • GROUP BY ROLLUP (aType) 应该在 Sybase 中工作
  • 谢谢rs。我收到错误:“未找到函数 'ROLLUP'。如果这是 SQLJ 函数或 SQL 函数,请使用 sp_help...”
  • @Matt 。 . .什么版本的 Sybase?

标签: sap-ase


【解决方案1】:

您是否尝试过只使用类似于此的UNION ALL

select aType, Rev
from
(
  SELECT aType, SUM(Earnings - Expenses) "Rev", 0 SortOrder
  FROM aTable
  GROUP BY aType
  UNION ALL
  SELECT 'All', SUM(Earnings - Expenses) "Rev", 1 SortOrder
  FROM aTable
) src
ORDER BY SortOrder, aType

SQL Fiddle with Demo。这给出了结果:

| ATYPE | REV |
---------------
|     A |  10 |
|     B | 150 |
|     C | 250 |
|   All | 410 |

【讨论】:

    【解决方案2】:

    也许你可以在 sybase 中使用 compute by 子句,例如:

    create table #tmp1( name char(9), earning int , expense int) 
    insert into #tmp1 values("A",30,20)
    insert into #tmp1 values("B",50,30)
    insert into #tmp1 values("C",60,30)
    
    select name, (earning-expense) resv from #tmp1
    group by name
    order by name,resv
    compute sum(earning-expense)
    

    select name, convert(varchar(15),(earning-expense)) resv  from #tmp1
    group by name
    union all
    SELECT "------------------","-----"
    union all
    select "ALL",convert(varchar(15),sum(earning-expense)) from #tmp1
    

    谢谢, 戈帕尔

    【讨论】:

      【解决方案3】:

      并非所有版本的 Sybase 都支持 ROLLUP。你可以用老式的方式来做:

      with t as 
          (SELECT aType, SUM(Earnings - Expenses) "Rev"
           FROM aTable
           GROUP BY aType
          )
      select t.*
      from ((select aType, rev from t) union all
            (select NULL, sum(rev))
           ) t
      ORDER BY (case when atype is NULL then 1 else 0 end), aType ASC
      

      这是令人讨厌的蛮力方法。如果这个版本的 Sybase 不支持with,你可以这样做:

      select t.aType, t.Rev
      from ((SELECT aType, SUM(Earnings - Expenses) "Rev"
             FROM aTable
             GROUP BY aType
            ) union all
            (select NULL, sum(rev))
           ) t
      ORDER BY (case when atype is NULL then 1 else 0 end), aType ASC
      

      这是非常基本的标准 SQL。

      【讨论】:

      • 这仍然不起作用,即使附加了 ;在前面,就像 SQL (stackoverflow.com/questions/13357366/…) 中的情况一样。此外,我尝试使用临时表来使用它,但仍然没有好处:/
      • @Matt 。 . .多么令人沮丧。我的猜测是您的 Sybase 版本不支持 with 语句。
      • 看起来是这样的!管理员控制也超出了我的控制,感谢队友的帮助,感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 2017-06-22
      • 1970-01-01
      • 2014-06-06
      • 2022-01-14
      相关资源
      最近更新 更多