当我们要查询明细和总计的时候,通常使用的方法是
方法一:
select item ,sum(xx) from xxx group by item
union
select null ,sum(xx) from xxx
方法二:
但是SQL server其实有两个简单的函数可以实现上面的功能
Rollup ():分组同时求明细
Grouping():判断是否是分组的列,1表示聚合列,0表示不是
代码:
SELECT grouping(StoreID)grouptag,StoreID,sum(sales)
FROM xxx
where storeid in (1xx ,26xx,
26xx
)
and SalesDate between '20190801' and '20190808'
group by rollup(StoreID)
结果:

方法三:
使用cube也可以达到同样的效果
代码
:
SELECT grouping(StoreID)grouptag,StoreID,sum(sales)
FROM xxxx
where storeid in (1xx ,26xx,
26xx
)
and SalesDate between '20190801' and '20190808'
group by StoreID with cube
结果

本文介绍了三种在SQL Server中查询明细数据与总计的有效方法,包括使用GROUP BY、ROLLUP()、GROUPING()及CUBE函数,展示了如何通过简洁的SQL语句实现复杂的数据汇总需求。

1963

被折叠的 条评论
为什么被折叠?



