0

询问:

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,但我不确定是否有其他方法可以做到这一点,如果有的话。

谢谢!

4

3 回答 3

1

并非所有版本的 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。

于 2013-02-12T01:48:29.550 回答
1

可能您可以在 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

谢谢,戈帕尔

于 2013-02-12T11:04:20.953 回答
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 |
于 2013-02-12T11:10:00.560 回答