T-SQL查找两行的百分比/比率

时间:2013-08-13 13:49:47

标签: sql-server tsql sql-server-2008-r2 pivot pivot-table

所以我有以下代码

SELECT CASE 
         WHEN ( ORG_CODE_PROV = 'ABC' ) THEN 'DEF' 
         ELSE ORG_CODE_PROV 
       END      AS ORG_CODE_PROV , 
       THE_DATE, 
       CASE 
         WHEN ( THE_NUMBER > '1' ) THEN 'Valid' 
         ELSE 'Invalid' 
       END      AS THE_NUMBER, 
       Count(*) AS Amount 
FROM   THE_TABLE
GROUP  BY ORG_CODE_PROV , 
          CASE 
            WHEN ( ORG_CODE_PROV = 'ABC' ) THEN 'DEF' 
            ELSE ORG_CODE_PROV 
          END, 
          THE_DATE, 
          CASE 
            WHEN ( THE_NUMBER > '1' ) THEN 'Valid' 
            ELSE 'Invalid' 
          END 

它产生了一些东西(尽管有更多数据加载)

ORG_CODE_PROV | THE_DATE | THE_NUMBER | Amount
----------------------------------------------
ABC           | 201204   | Invalid    | 50
ABC           | 201204   | Valid      | 200
ABC           | 201205   | Valid      | 200
ABC           | 201206   | Invalid    | 50
ABC           | 201206   | Valid      | 100
ZYZ           | 201204   | Invalid    | 20
XYZ           | 201204   | Valid      | 200

但我想要的是显示无效“数字”与总数的百分比。

ORG_CODE_PROV | THE_DATE | THE_PERCENTAGE
----------------------------------------------
ABC           | 201204   | 20    
ABC           | 201205   | 0
ABC           | 201206   | 33
ZYZ           | 201204   | 9

我猜我可能不得不使用数据透视表但却严重陷入困境。有什么帮助吗?

谢谢,

JJ

[编辑] ORG_CODE_PROV值已知,因为它们包含在更接近行的IN子句中。不确定这是否有帮助?

2 个答案:

答案 0 :(得分:1)

select 
    ORG_CODE_PROV,
    THE_DATE,
    100.0 * SUM(case the_number when 'invalid' then amount else 0 end) /
    nullif(SUM(amount),0)    
from 
(
     Select * from yourquery
) results
group by
    ORG_CODE_PROV,
    THE_DATE

答案 1 :(得分:0)

您可以在Count()中进行计算,如下所示:

SELECT CASE 
     WHEN ( ORG_CODE_PROV = 'ABC' ) THEN 'DEF' 
     ELSE ORG_CODE_PROV 
   END AS ORG_CODE_PROV, 
   THE_DATE, 
   COUNT( CASE WHEN ( THE_NUMBER > '1' ) THEN NULL ELSE 1 END ) / COUNT( * ) AS THE_PERCENT -- % Invalid
--, COUNT( CASE WHEN ( THE_NUMBER > '1' ) THEN 1 END ) / COUNT( * ) AS THE_OTHER_PERCENT -- % Valid
FROM THE_TABLE
GROUP BY CASE 
     WHEN ( ORG_CODE_PROV = 'ABC' ) THEN 'DEF' 
     ELSE ORG_CODE_PROV 
   END, THE_DATE