在减去时将大括号添加到负值

时间:2012-12-05 11:55:09

标签: sql

如何将花括号添加到负值,这将是减去两列的结果,

假设我有三列

        A      B           result(B-A)
-----------------------------------------
        1      4             3

        2      1            -1 [should be displayed as (1) not -1]

        9      3            (6)
-----------------------------------------
total   3      5            (4)

如何在选择查询中执行此操作?

2 个答案:

答案 0 :(得分:1)

如果你使用sql server试试这个:

select case  
       when (b-a) < 0 then  '{ ' + substring(CONVERT(NVARCHAR,(b-a)),2,2 ) +  '}' 
       else   CONVERT(nvarchar(max),(b -a)) END as result
from table

答案 1 :(得分:0)

查询:

<强> SQLFIddleExample

SELECT
t1.A,
t1.B,
CASE WHEN t1.B-t1.A<0 
      THEN '('+CAST( (t1.B-t1.A)*-1 as varchar(5))+')'
      ELSE CAST( t1.B-t1.A as varchar(5))  END AS result
FROM tbl t1

结果:

| A | B | RESULT |
------------------
| 1 | 4 |      3 |
| 2 | 1 |    (1) |
| 9 | 3 |    (6) |