分享

SQL Server的Compute和Compute By子句

 KILLKISS 2013-01-15

Compute和Compute By子句

既显示明细,也显示小计

1.Compute

select t.city, t.num

from

(

select 'wuhan' as city, 20 as num

union all

select 'guangzhou' as city, 30 as num

union all

select 'wuhan' as city, 40 as num

union all

select 'guangzhou' as city,  50 as num

) t

compute sum(t.num)

结果:

city num

wuhan 20
guangzhou 30
wuhan 40
guangzhou 50

sum

140

select t.city, t.type, t.num

from

(

select 'wuhan' as city, 'book' as type, 20 as num

union all

select 'guangzhou' as city, 'clothes' as type, 30 as num

union all

select 'wuhan' as city, 'clothes' as type, 40 as num

union all

select 'guangzhou' as city, 'book' as type, 50 as num

) t

compute(t.num)

结果:

出错,说明compute只能按照一个维度进行度量(要么city, 要么type),compute by同样。

 

2.Compute By子句--必须配合order by使用

select t.city, t.num

from

(

select 'wuhan' as city, 20 as num

union all

select 'guangzhou' as city, 30 as num

union all

select 'wuhan' as city, 40 as num

union all

select 'guangzhou' as city,  50 as num

) t

order by t.city

compute sum(t.num) by t.city

结果:

city num

guangzhou 30
guangzhou 50

sum

80

city num

wuhan 20
wuhan 40

sum

60

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多