SQL查询输出-十进制位置,整数过多



我有一个查询运行正常,我正在组合两个表,删除重复项并保留最新生效日期的数据。

表格如下:

1.TAX_TABLE---------    
tax_id  description
1   AZ State
2   AZ-Maricopa Co
4   AZ-Maricopa/Mesa

2.Tax_RATE_TABLE-------
tax_id  effective_date  tax_percent
1   2015-01-01 00:00:00.000 5.6
2   2015-01-01 00:00:00.000 0.7
4   2015-01-01 00:00:00.000 1.75
4   2019-03-01 00:00:00.000 2

我当前的查询如下:

use lhsitedb
select t.tax_id, t.description, tr.effective_date, tr.tax_percent
from dbo.tax t
inner join dbo.tax_rate tr on tr.tax_id = t.tax_id
where tr.effective_date = (
select max(tr1.effective_date)
from dbo.tax_rate tr1
where tr1.tax_id = tr.tax_id

我的输出是这样的,在tax_tax百分比列中得到小数。我一直在尝试对该列进行限制,使其仅显示可以放大到百分之一的十进制数字。

注意:当在SSMS中执行时,这个查询工作得很好,但是,我正在使用sqlcmd并将文件导出到.txt文件中,这就是产生这些意外结果的地方。

tax_id                description                     effective_date          tax_percent             
--------------------- ------------------------------- ----------------------- ------------------------
4 AZ-Maricopa/Mesa                2019-03-01 00:00:00.000                        2
2 AZ-Maricopa Co                  2015-01-01 00:00:00.000      0.69999999999999996
1 AZ State                        2015-01-01 00:00:00.000       5.5999999999999996
(17 rows affected)

当那一列,应该更多地沿着这些线看:

tax_percent  
----------------------------
2 
1.75 

更新了我的答案以使用CONVERT函数。。。

我会尝试使用CONVERT函数。。试试看!2将指定百分之一。CONVERT(DECIMAL(10,2),tr.tax_percent) as 'tax_percent'

use lhsitedb
select t.tax_id, t.description, tr.effective_date, 
CONVERT(DECIMAL(10,2),tr.tax_percent) AS 
'tax_percent' 
from dbo.tax t
inner join dbo.tax_rate tr on tr.tax_id = t.tax_id
where tr.effective_date = (
select max(tr1.effective_date)
from dbo.tax_rate tr1
where tr1.tax_id = tr.tax_id

首先,您可以使用apply简化查询。

其次,您似乎将这些值存储为floats,而不是decimal/numeric。好吧,你可以在输出上解决这个问题:

select t.tax_id, t.description, tr.effective_date,
round(tr.tax_percent, 2)
from dbo.tax t cross apply
(select top (1) tr.*
from dbo.tax_rate tr 
where tr.tax_id = t.tax_id
order by tr.effective_date desc
) tr

根据文档:"浮点数据是近似的;因此,并不是所有数据类型范围内的值都能准确表示。"floatreal都会出现一些显示异常。

我会尝试一个明确的CAST。类似于:

use lhsitedb
select 
t.tax_id, 
t.description, 
tr.effective_date, 
CAST(tr.tax_percent AS decimal(18,2)) AS tax_percent --<-- The only change is here.
from dbo.tax t
inner join dbo.tax_rate tr on tr.tax_id = t.tax_id
where tr.effective_date = (
select max(tr1.effective_date)
from dbo.tax_rate tr1
where tr1.tax_id = tr.tax_id

您可以使用str((

https://learn.microsoft.com/en-us/sql/t-sql/functions/str-transact-sql?redirectedfrom=MSDN&view=sql-server-ver15

str(your_value, 3, 2);  

select t.tax_id, t.description, tr.effective_date, str(tr.tax_percent,3,2)

最新更新