为什么我收到 "Conversion failed when converting date and/or time from character string."?

Why am I receiving "Conversion failed when converting date and/or time from character string."?

当我 运行 此查询时,我想对 [订单数] 和 [总收入] 的查询天数求和。但是我在 sql 服务器 "Conversion failed when converting date and/or time from character string".

中收到此错误

我的代码是这样的:

select  TaxDate [Date]
        ,count(docentry) [# of Orders]
        ,sum(doctotal)-(SUM(TotalExpns)+SUM(VatSum)) [$]

from ORDR

where   CANCELED<>'Y'
        and SlpCode = '37'
        and TaxDate >= '2015-05-26'
        and DocStatus = 'C'

GROUP BY TaxDate

UNION ALL

select  'Total'
        ,SUM(docentry)
        ,sum(doctotal)-(SUM(TotalExpns)+SUM(VatSum))

from ORDR

where   CANCELED<>'Y'
        and SlpCode = '37'
        and TaxDate >= '2015-05-26'
        and DocStatus = 'C'

group by TaxDate
order by TaxDate

我对编写查询还很陌生。我没有使用 "UNION" 工具的经验。所以我很感激任何关于这方面的建议。

您有一个 union all,第一个子查询中有日期,第二个子查询中有 'Total'。 SQL 服务器决定两者都应该是日期,因此您在 'Total' 上收到转换错误。

它们必须是同一类型。尝试将第一个更改为:

select convert(varchar(10), TaxDate, 121) as [Date],
       count(docentry) [# of Orders],
       sum(doctotal)-(SUM(TotalExpns)+SUM(VatSum)) [$]

无论如何,您不需要 union all 来进行此查询。我认为 with rollup 做你想做的事:

select  TaxDate [Date], count(docentry) [# of Orders],
        sum(doctotal)-(SUM(TotalExpns)+SUM(VatSum)) [$]
from ORDR
where CANCELED <> 'Y' and SlpCode = '37' and TaxDate >= '2015-05-26' and
      DocStatus = 'C'
group by TaxDate with rollup;

您收到此错误是因为在 UNION 的第二个查询中,您的第一列明确是 VARCHAR,但在您的第一个查询中,它是 DATE。这些数据类型需要匹配。

我建议执行以下操作:

select  Cast(TaxDate As Varchar (10)) [Date]
        ,count(docentry) [# of Orders]
        ,sum(doctotal)-(SUM(TotalExpns)+SUM(VatSum)) [$]

from ORDR

where   CANCELED<>'Y'
        and SlpCode = '37'
        and TaxDate >= '2015-05-26'
        and DocStatus = 'C'

GROUP BY TaxDate

UNION ALL

select  'Total'
        ,SUM(docentry)
        ,sum(doctotal)-(SUM(TotalExpns)+SUM(VatSum))

from ORDR

where   CANCELED<>'Y'
        and SlpCode = '37'
        and TaxDate >= '2015-05-26'
        and DocStatus = 'C'

group by TaxDate
order by [Date]