1

当我运行此查询时,我想计算 [订单数量] 和 [总收入] 的查询天数。但是我在我的 sql 服务器中收到此错误“从字符串转换日期和/或时间时转换失败”。

我的代码是这样的:

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”工具的经验。所以我很感激任何关于这方面的建议。

4

2 回答 2

5

union all在第一个子查询和'Total'第二个子查询中有一个日期。SQL Server 决定两者都应该是日期,因此您在'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;
于 2015-07-29T20:48:53.287 回答
0

您收到此错误是因为在您的第二个查询中UNION,您的第一列明确是 a VARCHAR,但在您的第一列中,它是 a 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]
于 2015-07-29T20:50:05.570 回答