使用汇总来计算总计,同时显示月份名称并按月份编号排序

时间:2018-11-24 15:04:59

标签: sql sql-server

此内容改编自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);

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

结果是这样的:

enter image description here

我希望订单为一月,二月等。

1 个答案:

答案 0 :(得分: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);