As I asked in this question : Oracle SQL Group By if I log file usage in my application. There is 3 files sources:
- Pool
- MDA
- Other
If the file is opened twice from MDA and once from Pool, I'll get two entries:
TESTID SITE LATEST_READ READ_COUNT FILE_ORIGIN_ID
------------- ---------- ----------- ---------- --------------
File1 |Site1 |02/05/13 | 2| 1
File1 |Site2 |22/01/14 | 3| 2
What I want to achieve is to get the ratio of files that are not in the Pool OR the MDA grouped by sites. So I managed to do this resquest:
SELECT Count(TESTID) as OTHER_FILES, SITE, 'OTHERS'
FROM USER_STATS.FILE_USAGE_LOG
WHERE TESTID not in (
-- Files that are on Pool OR MDA
SELECT TESTID
FROM USER_STATS.FILE_USAGE_LOG
WHERE FILE_ORIGIN_ID < 2
)
AND LATEST_READ between '01/05/2015' and '01/06/2015'
GROUP BY Site
UNION ALL
SELECT Count(TESTID) as OTHER_FILES, site, 'Files that are at least in Pool or MDA'
FROM USER_STATS.FILE_USAGE_LOG
WHERE TESTID in (
-- Files that are on Pool OR MDA
SELECT TESTID
FROM USER_STATS.FILE_USAGE_LOG
WHERE FILE_ORIGIN_ID < 2
)
AND LATEST_READ between '01/05/2015' and '01/06/2015'
GROUP BY Site
Which gives me this:
18 BR-CTA Files that are at least in Pool or MDA
324 BR-CTA OTHERS
26 BR-CTA-VPN OTHERS
5 CN-TSN-VPN OTHERS
2040 FR-LYON Files that are at least in Pool or MDA
248 FR-LYON OTHERS
1 IN-BLR Files that are at least in Pool or MDA
1 IN-PUNE OTHERS
810 JP-SAIT OTHERS
48 JP-SAIT Files that are at least in Pool or MDA
...
And I would like to have this:
94% BR-CTA Ratio -- 94% in OTHER
100% BR-CTA-VPN Ratio -- 100% in OTHER
100% CN-TSN-VPN Ratio -- 100% in OTHER
10% FR-LYON Ratio -- 10% in OTHER
0% IN-BLR Ratio -- 0% in OTHER
100% IN-PUNE Ratio -- 100% in OTHER
94% JP-SAIT Ratio -- 94% in OTHER
...
But I can't acheive this whatever I try. How can I do this?
I use nbTotal / (nbOther) * 100
as ratio calculation.
There's a few ways to do that and what is possible or best depends in part on you RDBMS. However, here is one way. I am substituting you query above with an IntermediateResults table for simplicity. In practice you could use your query with a CTE, derived table, temp table or table variable.
Results:
EDIT: An example of how to replace the table in my example with your query would be to use a subquery factoring which is what Oracle calls TSQL Common Table Expression or the WITH construct.