Search code examples
sqlsap-aserankwindow-functions

Alternative to window functions in Sybase


I have the below query

  SELECT M_PILLAR,
       M_MXCOUNTRY,
       M_LIMIT_NETEXPOSURE,
       M_LIMIT_CURRENCY_NETEXPOSURE,
       M_MAXUTILIZATION_NETEXPOSURE,
       M_AVAILABLE_NETEXPOSURE,
       M_GROUP,
       M_ENTITIES,
       M_COUNTERPARTIES,
       rank() OVER (partition BY M_COUNTERPARTIES,M_PILLAR,M_MAXEXPOSURE_NETEXPOSURE) AS test
FROM X_LP_PSR_REP

But it looks like my Sybase DB does not support window functions.

I tried the following:

SELECT M_PILLAR,
   M_MXCOUNTRY,
   M_LIMIT_NETEXPOSURE,
   M_LIMIT_CURRENCY_NETEXPOSURE,
   M_MAXUTILIZATION_NETEXPOSURE,
   M_AVAILABLE_NETEXPOSURE,
   M_GROUP,
   M_ENTITIES,
   M_COUNTERPARTIES,
   rank() OVER (ORDER BY M_COUNTERPARTIES,M_PILLAR,M_MAXEXPOSURE_NETEXPOSURE) AS test FROM X_LP_PSR_REP

replaced "partition by" with "order by" did not work also.

Please advise on how to proceed.

I am using Sybase ASE

The exact version is:

Adaptive Server Enterprise/15.7.0/EBF 21207 SMP SP50 /P/Solaris AMD64/OS 5.10/ase157sp5x/3284/64-bit/FBO/Thu Jul 11 07:19:59 2013


Solution

  • You can do this with a correlated subquery (albeit, much less efficiently). For rank() (using the second example which uses ORDER BY and is syntactically correct), this looks like:

    SELECT r.*,
           (SELECT 1 + COUNT(*)
            FROM X_LP_PSR_REP r2
            WHERE (r2.M_COUNTERPARTIES < r.M_COUNTERPARTIES) OR
                  (r2.M_COUNTERPARTIES = r.M_COUNTERPARTIES AND r2.M_PILLAR < r.M_PILLAR) OR
                  (r2.M_COUNTERPARTIES = r.M_COUNTERPARTIES AND r2.M_PILLAR = r.M_PILLAR AND r2.M_MAXEXPOSURE_NETEXPOSURE < r.M_MAXEXPOSURE_NETEXPOSURE)
           ) as test
    FROM X_LP_PSR_REP r;