How ‘group’ attribute works while looping a query coldfusion script?
We use group attribute to remove adjacent duplicate values in a ‘cfloop’. Let’s see a simple sytax of group attribute.
Syntax :
cfloop( query = "QueryName", group = "queryColumnName" ){
............
............
}
Explanation:
queryColumnName is any column name of the query through which we can avoid duplicate adjacent rows.
Let’s understand with two examples:
Example 1 :
<cfscript>
myQuery = queryNew("id,name,amount","Integer,Varchar,Integer",
[
{id=1,name="One",amount=15},
{id=1,name="NotOne",amount=16},
{id=2,name="Two",amount=18},
{id=3,name="Three",amount=32}
]);
cfloop( query = "myQuery", group = "id" ){
writeOutput("#id#.#name#<br>");
}
</cfscript>
Output:
1.One
2.Two
3.Three
Explanation:
We can see first two structures ( {id=1,name=”One”,amount=15}, {id=1,name=”NotOne”,amount=16} ) are not fully same but they have same id ( We did the group through id column in cfloop ) and are adjacent. So only first row 1.One is selected for both two.
Example 2 :
<cfscript>
myQuery = queryNew("id,name,amount","Integer,Varchar,Integer",
[
{id=1,name="One",amount=15},
{id=2,name="Two",amount=18},
{id=1,name="NotOne",amount=16},
{id=3,name="Three",amount=32}
]);
cfloop( query = "myQuery", group = "id" ){
writeOutput("#id#.#name#<br>");
}
</cfscript>
Output:
1.One
2.Two
1.NotOne
3.Three
Explanation:
For this case {id=1,name=”One”,amount=15} and {id=1,name=”NotOne”,amount=16} have same id but they are not adjacent, so we have got two lines 1.One and 1.NotOne.