我在结合使用 `with rollup` 和 `GROUPING` 时遇到问题。如何纠正?

I am having issues combining `with rollup` and `GROUPING`. How to correct?

最近有人向我介绍了一项名为 with rollup 的功能。我将添加到我在 Excel 中使用的趋势报告中。问题是,我希望 t0.DocDate 的日期从最旧到最新排序。

我读了一篇文章:http://mangalpardeshi.blogspot.com/2009/08/rollup-and-order-by.html

我将我的代码格式化为类似于文章中的示例,但在这样做之后我收到此错误消息:Conversion failed when converting date and/or time from character string.

有什么方法可以更正查询中的这个错误吗?如果是这样,任何可以帮助我的人都将不胜感激!

我的代码是:

select  CASE WHEN GROUPING(t0.DocDate) = 1 THEN 'Total' ELSE T0.DocDate END AS 'DocDate',
        COUNT(T1.Itemcode) [# of Cross Sell],
        SUM(T1.Price * t1.Quantity) [Cross Sell $]

from ORDR t0 inner join RDR1 t1 on t0.DocEntry=t1.DocEntry

where t0.CANCELED <> 'Y'
and t1.U_SII_XSell = 'Y'

group by t0.DocDate WITH ROLLUP
order by GROUPING(t0.docdate);

如果您希望将 'Total' 用作汇总列值,则需要将 DocDate 转换为 VARCHAR。该列不能是两种类型。

然后要按日期排序,并将总计列放在最后,您只需将 t0.DocDate 添加到 ORDER BY 子句。

select  CASE WHEN GROUPING(t0.DocDate) = 1 THEN 'Total' ELSE Cast(T0.DocDate As Varchar(15)) END AS 'DocDate',
        COUNT(T1.Itemcode) [# of Cross Sell],
        SUM(T1.Price * t1.Quantity) [Cross Sell $]

from ORDR t0 inner join RDR1 t1 on t0.DocEntry=t1.DocEntry

where t0.CANCELED <> 'Y'
and t1.U_SII_XSell = 'Y'

group by t0.DocDate WITH ROLLUP
order by GROUPING(t0.docdate), t0.docdate;