SQL查询的时候同时显示明细和总计 |
您所在的位置:网站首页 › sql计算一列的总和 › SQL查询的时候同时显示明细和总计 |
当我们要查询明细和总计的时候,通常使用的方法是 方法一: 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结果 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |