1

可能重复:
SQL:计算输出列上出现的次数并根据出现次数计算某个百分比

这是测试数据/表格的网址:http ://sqlfiddle.com/#!2/56ffd4/1

我的表为下表生成 o/p:

(id,       resolution) 
('abc-123', 'fail'),
('abc-456', 'pass'),
('abc-789', 'pass'),
('abc-799', 'fail'),
('abc-800', 'pass'),
('abc-900', 'pass');

我的脚本 o/p 是:

id          RESOLUTION  TS              @PREV   C   RES
abc-123     fail    July, 02 2012         1     1   -
abc-456     pass    July, 02 2012         2     0   50.00%
abc-789     pass    July, 02 2012         1     0   100.00%
abc-799     fail    July, 02 2012         1     1   -
abc-800     pass    July, 02 2012         2     0   50.00%
abc-900     pass    July, 02 2012         0     0   100.00%

这是 o/p 脚本:

SELECT st.*, 
       @prev:=@counter + 1,
       @counter:= CASE 
         WHEN st.resolution = 'pass'
         THEN 0
         ELSE @counter + 1
       END c,
       CASE WHEN @counter = 0 
            THEN CONCAT(FORMAT(100/@prev, 2), '%') 
            ELSE '-' 
       END res
  FROM so_test st, (SELECT @counter:=0) sc

我需要将两列附加到上面的输出表中,以计算传递值和失败值的出现次数:

id          RESOLUTION  TS              @PREV   C            fail   pass
    abc-123     fail    July, 02 2012         1     1   -        1
    abc-456     pass    July, 02 2012         2     0   50.00%          1
    abc-789     pass    July, 02 2012         1     0   100.00%         1
    abc-799     fail    July, 02 2012         1     1   -        1
    abc-800     pass    July, 02 2012         2     0   50.00%          1
    abc-900     pass    July, 02 2012         0     0   100.00%         1
4

1 回答 1

1

好吧,如果您只想要输出表末尾的通过和失败列,就像您指定的那样,那么在后面加上一个逗号

END res 

并在其后添加以下内容:

CASE WHEN st.resolution = 'fail'
            THEN 1
            ELSE NULL
END fail,
CASE WHEN st.resolution = 'pass'
            THEN 1
            ELSE NULL
END pass

不确定您的列中的空白是什么,但我只是将它们设置为 NULL。

于 2012-07-03T00:48:11.937 回答