0

So I have the following code

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 

It produces something along the lines of (allbeit with a load more data)

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

What I would like however is to show the percentage of invalid 'numbers' against the total e.g.

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

I'm guessing I might have to use a pivot table but got seriously stuck. Any help?

Thanks,

JJ

[EDIT] The ORG_CODE_PROV values are known as they are included in an IN clause further down the line. Not sure if that helps at all?

4

2 回答 2

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
于 2013-08-13T13:57:28.350 回答
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
于 2013-08-13T14:09:34.303 回答