Jump to content



Recommended Posts

I'm trying to search a string for all occurences of a pattern, then append text after that pattern.  The example is:


SUM("foo") as "bar"


and have it display as:


SUM("foo") over() as "bar"


The "SUM" could be any SQL aggregate and be case insensitive.  So For bonus points, let's say the valid aggregates are  array('SUM', 'MAX', 'MIN', 'AVG').  My plan right now is to figure it out for SUM, then loop it replacing the aggregate.


This is what I have so far... and it is not working.


$l= 'SUM("foo") as "bar"';

$l=preg_replace('/([^"]+")/','\0 over()',$l);





Link to comment
Share on other sites

Are "foo" and "bar" always going to be "foo" and "bar" or can they be variable text values?


EDIT: Also, you say the value inside the aggregate function may or may not have quotes. Can it use single quotes as well? And what about the quotes around "Bar" can that use single or double quotes - or no quotes?

Edited by Psycho
Link to comment
Share on other sites

I made some assumptions and made this so it would be very flexible

$functions = array('SUM', 'MAX', 'MIN', 'AVG');
$patterns = array();
$replacemetns = array();
foreach($functions as $func)
    $patterns[] = "#({$func})\(([^\)]*)\) as (\"){0,1}([^\"]*)(\"){0,1}#";
    $replacements[] = "\\1(\\2) over() \\3\\4\\5";
$output = preg_replace($patterns, $replacements, $input);

If this is your input

SELECT field1, field2, field3,
       SUM('field3') as 'field3sum',      --Single quotes
       MAX("field4") as "field4max",      --Double quote
       AVG(field5) as field5avg           --No quotes
FROM table_name

This will be the output

SELECT field1, field2, field3,
       SUM('field3') over() 'field3sum',  --Single quotes
       MAX("field4") over() "field4max",  --Double quote
       AVG(field5) over() field5avg       --No quotes
FROM table_name
Edited by Psycho
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.