我希望在查询[#of orders]&我运行此查询时的[总收入]。但我在我的sql server中收到此错误"从字符串"转换日期和/或时间时转换失败。
我的代码是:
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
我是编写查询的新手。我没有使用&#34; UNION&#34;工具。所以我对此有任何建议。
答案 0 :(得分: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;
答案 1 :(得分:0)
您收到此错误是因为在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]