Skip to content

Instantly share code, notes, and snippets.

@nrother
Last active October 4, 2016 21:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nrother/abd9f9499ecfe7a21db25e6409ccd2ae to your computer and use it in GitHub Desktop.
Save nrother/abd9f9499ecfe7a21db25e6409ccd2ae to your computer and use it in GitHub Desktop.
CREATE TABLE test
("id" int PRIMARY KEY, "title" varchar(5), "cat" varchar(2));
INSERT INTO test
("id", "title", "cat")
VALUES
(1, 'one', 'en'),
(2, 'two', 'en'),
(3, 'three', 'en'),
(4, 'vier', 'de'),
(5, 'fuenf', 'de'),
(6, 'sechs', 'de')
;
--see https://sqlperformance.com/2014/08/t-sql-queries/sql-server-grouped-concatenation
select stuff((select ',' + title from test where cat = "outer".cat for xml path(''), type).value('.[1]', 'varchar(max)'), 1, 1, '')
from (select title, cat from test) "outer"
group by cat
--need distinct if no group by present
select distinct stuff((select ',' + title from test for xml path(''), type).value('.[1]', 'varchar(max)'), 1, 1, '')
from test "outer"
--mysql
--select group_concat(title, ',')
--from test
--group by cat
;with cte(expr, rank) as
(select title, DENSE_RANK() OVER (ORDER BY cat) from test)
select stuff((select ',' + expr from cte where rank = "outer".rank for xml path(''), type).value('.[1]', 'varchar(max)'), 1, 1, '')
from cte "outer"
group by rank
<?php
/**
* Transforms the query as necessary if it contains a GROUP_CONCAT() expression.
*
* @param \Cake\Database\Query $original The query to be transformed
* @return \Cake\Database\Query
*/
protected function _transformGroupConcat($original)
{
$groupConcats = [];
foreach ($original->clause('select') as $expr) {
if ($expr instanceof FunctionExpression && $expr->name() === 'GROUP_CONCAT') {
$expr //reduce $expr no a no-op
->name('')
->iterateParts(function ($p, $key) {
return $key === 0 ? $p : null;
});
$groupConcats[] = $expr;
}
}
$inner = clone $original;
$inner
->select($original->clause('group'))
->group([], true);3
if (count($original->clause('group')) == 0) {
$original->distinct();
}
$original->from(['_cake_subquery' => $inner], true);
foreach($groupConcats as $expr) {
$subquery = clone $original;
$subquery
->select()
->epilog("FOR XML PATH(''), type"); //TODO...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment