如何在SQL Server中所有行的顶部显示“总”行的所有列的总和?

时间:2018-10-10 10:18:09

标签: sql-server

样本数据:

LocationCode    Name      NetSalesQty
01              holsale   24
B1              bhk vyas  24
d001            retail    24
Total           NULL      72

我想要在顶部具有固定的“总计”行的记录,如下所示:

LocationCode    Name      NetSalesQty
Total           NULL      72
01              holsale   24
B1              bhk vyas  24
d001            retail    24

这是我的SQL查询:

SELECT COALESCE(LocationMaster.LocationCode, 'Total') AS LocationCode,
       LocationMaster.Name,
       SUM(IdTableExtd.DocQty * IdTableExtd.StockSign) AS NetSalesQty
FROM IdTable
     INNER JOIN LocationMaster ON LocationMaster.LocationCode = IdTable.LocationCode
     INNER JOIN IdTableExtd ON IdTableExtd.LocationCode = IdTable.LocationCode    AND IdTableExtd.StockNo = IdTable.StockNo
WHERE IdTableExtd.DocDate BETWEEN '2018-10-07 ' AND '2018-10-10 '
GROUP BY ROLLUP(LocationMaster.LocationCode, LocationMaster.Name);

1 个答案:

答案 0 :(得分:2)

您可以使用order by子句:

select t.*
from table t
order by (case when name is null then 0 else 1 end), LocationCode;