Search code examples
coldfusioncfmlcfquerycfloop

How to output query value only once?


I have query that returns four columns. One of the columns can have the same value for multiple records. I would like to output that value only once. Here is example of the data:

Rec ID  Name   Color  Year
45      Nick   Green  2018
34      Mike   Red    2018
37      Nick   Blue   2019
44      John   Pink   2019
23      Jimmy  Orange 2019

I uses this code to output the values:

<cfoutput>
  <cfloop query="myQuery">
     <cfif fiscal_year gt 1991>
        <tr>    
            <td colspan="4"><a href="new_page.cfm?year=#year#>View All</a></td>
        </tr>
     </cfif>
     <tr>
        <td>#rec_id#</td>
        <td>#name#</td>
        <td>#color#</td>
        <td>#year#</td>
     </tr>
   </cfloop>
</cfoutput>

My output looks like this:

View All
45      Nick   Green  2018
View All
34      Mike   Red    2018
View All
37      Nick   Blue   2019
View All
44      John   Pink   2019
View All
23      Jimmy  Orange 2019

Instead I would like my output too look like this:

View All
45      Nick   Green  2018
34      Mike   Red    2018
View All
37      Nick   Blue   2019
44      John   Pink   2019
23      Jimmy  Orange 2019

What is the easiest way to achieve this?


Solution

  • The <cfoutput> tag has a group attribute that allows you to group your query data by a column. You can nest the grouped data in another <cfoutput> tag and even group by multiple columns. It should look something like this:

    <cfoutput query="myQuery" group="year">
        <cfif fiscal_year gt 1991>
            <tr>    
                <td colspan="4"><a href="new_page.cfm?year=#year#">View All</a></td>
            </tr>
        </cfif>
        <cfoutput>
        <tr>
            <td>#rec_id#</td>
            <td>#name#</td>
            <td>#color#</td>
            <td>#year#</td>
        </tr>
        </cfoutput>
    </cfoutput>