SQL ROUND十进制并显示为varchar

时间:2017-04-23 23:23:44

标签: sql-server decimal rounding

我的表中有一些十进制字段。我正在尝试将它们翻转并以所需的格式显示。这是一个例子:

CREATE TABLE #SummaryData(
[ColA] [decimal](18, 1) NULL,
[ColB] [decimal](18, 2) NULL,
[ColC] [decimal](18, 4) NULL,
[ColD] [decimal](18, 4) NULL,
[ColE] [decimal](18, 4) NULL
)

INSERT INTO #SummaryData ([ColA],[ColB],[ColC],[ColD],[ColE])
VALUES (36754.0 ,9090.07,   2.4507  ,33536.0000 ,0.0073)

INSERT INTO #SummaryData ([ColA],[ColB],[ColC],[ColD],[ColE])
VALUES (54978.0 , 12535.32  , 9.9419,47041.0000,    0.0088)

INSERT INTO #SummaryData ([ColA],[ColB],[ColC],[ColD],[ColE])
VALUES (53501.0,    13346.62,   2.8152, 32371.0000, 0.0042)

SELECT [ColA],[ColB],[ColC],[ColD],[ColE] 
FROM #SummaryData


-- We need data to be displayed like this for the purpose of reporting
ColA      ColB         ColC   ColD    ColE
----------------------------------------
36,754     9090        2.46   33.5%   0.7%

我尝试使用ROUND并转换为varchar但不起作用。不确定如何在小数点后删除零并应用"," (逗号)。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

SELECT SUBSTRING(CONVERT(VARCHAR, CAST(cola as money), 1), 1, LEN(CONVERT(VARCHAR, CAST(cola as money), 1)) - 3) AS ColA, 
    CONVERT(INT, ColB) AS ColB,
    CONVERT(NUMERIC(18,2), ColC) AS ColC, 
    FORMAT(ColD / 100000., 'p1') AS ColD, 
    FORMAT(ColE, 'p1') AS ColE
FROM #SummaryData

这是输出:

36,754   9090    2.45   33.5 %   0.7 %
54,978   12535   9.94   47.0 %   0.9 %
53,501   13346   2.82   32.4 %   0.4 %

答案 1 :(得分:1)

SELECT FORMAT(ColA, '#,###')  AS ColA, 
    CAST(ColB AS INT) AS ColB,
    CAST(ColC AS INT) AS ColC, 
    FORMAT(ColD / 100000., 'p1') AS ColD, 
    FORMAT(ColE, 'p1') AS ColE
FROM #SummaryData


The output is:

ColA    ColB    ColC    ColD    ColE
36,754  9090    2       33.5 %  0.7 %
54,978  12535   9       47.0 %  0.9 %
53,501  13346   2       32.4 %  0.4 %