gpt4 book ai didi

SQL 服务器计数

转载 作者:行者123 更新时间:2023-12-01 14:01:10 24 4
gpt4 key购买 nike

我有以下查询:

select col1, sum( col2 ), count( col3 )
from table1
group by col1
order by col1

它返回这样的东西

col1
dept1
dept2
dept3

col2
10
20
30

col3
2
3
4

如果没有存储过程,是否可以得到原始查询生成的结果下面的总计列?

col1
dept1
dept2
dept3
total

col2
10
20
30
60

col3
2
3
4
9

最佳答案

使用ROLLUP :

;with Table1 as (
select 'dept1' as col1, 5 as col2,1 as col3
union all
select 'dept1', 5 as col2, 1 as col3
union all
select 'dept2',10,1
union all
select 'dept2',5,1
union all
select 'dept2',5,1
union all
select 'dept3',10,1
union all
select 'dept3',5,1
union all
select 'dept3',5,1
union all
select 'dept3',10,1
)
select COALESCE(col1,'total'), sum( col2 ), count( col3 )
from table1
group by col1
with rollup
order by COALESCE(col1,'ZZZZZ')

结果:

(No column name)    (No column name)    (No column name)
dept1 10 2
dept2 20 3
dept3 30 4
total 60 9

关于SQL 服务器计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6451648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com