如何添加汇总行的新列

How to add a new column that summarize rows

我有两个问题:

  1. 我使用 'Rollup' 函数添加每月和每年的总计,我想将 'NULL' 更改为 grand_total,如所附屏幕截图

  2. 我不知道如何添加一个新列来汇总从第二行开始的值

请参阅随附的我需要接收的结果的屏幕截图以及我这边的代码示例以及源输出的屏幕截图:[1]:https://i.stack.imgur.com/6B70o.png [1]: https://i.stack.imgur.com/E2x8K.png

Select Year(Modifieddate) AS Year,
       MONTH(modifieddate) as Month,
       Sum(linetotal) as Sum_price
from Sales.SalesOrderDetail
Group by  rollup( Year(Modifieddate),MONTH(modifieddate))

提前致谢,

像这样:

Select Year(Modifieddate) AS Year, MONTH(modifieddate) as Month, Sum(linetotal) as Sum_price 
from Sales.SalesOrderDetail 
Group by rollup( Year(Modifieddate),MONTH(modifieddate))
UNION 
Select Year(Modifieddate) AS Year, 'grand_total' as Month, Sum(linetotal) as Sum_price 
from Sales.SalesOrderDetail 
Group by Year(Modifieddate)
-- SQL SERVER
SELECT t.OrderYear
     , CASE WHEN t.OrderMonth IS NULL THEN 'Grand Total' ELSE CAST(t.OrderMonth AS VARCHAR(20)) END b
     , t.MonthlySales
     , MAX(t.cum_total) cum_total
FROM (SELECT
    YEAR(OrderDate) AS OrderYear,
    MONTH(OrderDate) AS OrderMonth,
    SUM(SubTotal) AS MonthlySales,
    SUM(SUM(SubTotal)) OVER (ORDER BY YEAR(OrderDate), MONTH(OrderDate) ROWS UNBOUNDED PRECEDING) cum_total
    
FROM Sales.SalesOrderHeader
GROUP BY GROUPING SETS ((YEAR(OrderDate), MONTH(OrderDate)))) t
GROUP BY GROUPING SETS ((t.OrderYear
     , t.OrderMonth
     , t.MonthlySales), t.OrderYear);   

请检查这个urlhttps://dbfiddle.uk/?rdbms=sqlserver_2019&sample=adventureworks&fiddle=e6cd2ba8114bd1d86b8c61b1453cafcf

我认为这会起作用:

Select Year(Modifieddate) AS Year,
       coalesce(convert(varchar(255), month(modifieddate)), 'Grand Total') as Month,
       Sum(linetotal) as Sum_price,
       sum(sum(linetotal)) over (partition by Year(Modifieddate)
                                 order by coalesce(month(modifieddate), 100)
                                ) as ytd_sum_price
from Sales.SalesOrderDetail
Group by rollup( Year(Modifieddate), month(modifieddate))

order by中的coalesce()是将汇总行放在最后,用于累计和

要构建一个@GordonLinoff 的答案,您确实应该使用GROUPING() 函数 来检查您是否正在处理分组列。这在面对可为空的列时表现更好。

Select case when grouping(Year(Modifieddate)) = 0
         then Year(Modifieddate)
         else 'Grand Total' end AS Year,
       case when grouping(month(modifieddate)) = 0
         then convert(varchar(255), month(modifieddate))
         else 'Grand Total' end as Month,
       Sum(linetotal) as Sum_price,
       sum(sum(linetotal)) over (
            partition by
               grouping(Year(Modifieddate)),
               grouping(month(modifieddate)),
               Year(Modifieddate)
            order by month(modifieddate)
                                ) as ytd_sum_price
from Sales.SalesOrderDetail
Group by rollup( Year(Modifieddate), month(modifieddate));