【问题标题】:USE ROLLUP to compute grand total while displaying month names and sorting by month number使用 ROLLUP 计算总计,同时显示月份名称并按月份编号排序
【发布时间】:2018-11-24 15:04:58
【问题描述】:

本文改编自https://www.databasejournal.com/features/mssql/using-the-rollup-cube-and-grouping-sets-operators.html

这是我所拥有的:

SELECT DATENAME(month, PurchaseDate) PurchaseMonth
     , CASE WHEN DATENAME(month, PurchaseDate) is null then 'Grand Total' 
                   ELSE coalesce (PurchaseType,'Monthly Total') end AS PurchaseType
     , Sum(PurchaseAmt) as SummorizedPurchaseAmt
FROM tPurchaseItem
GROUP BY   ROLLUP(DATENAME(month, PurchaseDate), PurchaseType);

这有效,但不按时间顺序排序。

结果是这样的:

我希望订单是一月、二月等。

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    DATENAME 返回一个nvarchar,因此排序类似于nvarchar'April' < 'January'.

    一种方法是将您的 GROUP BY 更改为 DATEPART 并从数字中得出月份名称:

    SELECT CHOOSE(DATEPART(MONTH, PurchaseDate),'January','February','March','April','May','June','July','August','September','October','November','December') AS PurchaseMonth
         , CASE WHEN DATENAME(month, PurchaseDate) is null then 'Grand Total' 
                       ELSE coalesce (PurchaseType,'Monthly Total') end AS PurchaseType
         , Sum(PurchaseAmt) as SummorizedPurchaseAmt
    FROM tPurchaseItem
    GROUP BY   ROLLUP(DATEPART(MONTH, PurchaseDate), PurchaseType);
    

    【讨论】:

      猜你喜欢
      • 2014-02-24
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多