在报告中以小数形式表示是/否答案的计数

时间:2014-08-13 18:46:06

标签: sql sql-server case iif

我的报告看起来像这样:

Query Name           Attempts        Successes      Failures    SuccessProportion
First Query             1               0               1               0/1
Second Query            1               0               1               0/1
Third Query             2               1               1               1/2
Fourth Query            1               1               0               1/1
Fifth Query             1               0               1               0/1
Sixth Query             1               0               1               0/1

这是我创建报告的代码:

            l_strsql = "SELECT Query_Name, " +
                 " Attempts, " +
                 " Successes, " +
                 " Failures, " +
                 " CAST([Successes] AS NVARCHAR(10)) + ' / ' + CAST([Attempts] AS NVARCHAR(10))  AS Proportion " + 
                 " FROM ( " +
          "SELECT generate_query AS Query_Name, " +
                 " sum(case when RecNum is NOT NULL then 1 else 0 end) AS Attempts, " +
                 " sum(case when export_TIR = 'Yes' then 1 else 0 end) AS Successes, " +
                 " sum(case when export_TIR = 'No' then 1 else 0 end) AS Failures " +
                 " FROM tbl_TPF " +
                 " WHERE export_type = 'Excel' " +
                 " GROUP BY generate_query " +
                 " ) Q ";

如何将SuccessProportion显示为小数点后2位的小数? - 有可能吗?

1 个答案:

答案 0 :(得分:2)

   " CAST([Successes] AS NVARCHAR(10)) + ' / ' + CAST([Attempts] AS NVARCHAR(10))  AS Proportion

该行将其设置为varchar,这是您看到的1/2格式。

             " CAST([Successes] AS numeric(8,2))  /  CAST([Attempts] AS numeric(8,2))  AS Proportion

应该将数值作为成功/尝试给出。没有0处理(尝试= 0表示div为0错误),但我怀疑你的查询是否会发生

编辑 - 最后一次演员以获得您想要的最终格式:

" cast(CAST([Successes] AS numeric(8,2))  /  CAST([Attempts] AS numeric(8,2))  as numeric(8,2))"