XSLT Version of SQL SELECT MAX() and SELECT MIN()
I’ve frequently encountered the need to produce titles for XSLT produced tables.
For example, given the following XML:
<events>
<event date="2004-11-30 14:00:00" />
<event date="2004-11-30 14:00:00" />
<event date="2003-11-30 14:00:00" />
<event date="2002-11-30 14:00:00" />
</events>
To extract the values “2002″ and “2004″ to format a title such as “Events (2002 > 2004)”.
To do this effectively requires us to extract both the MAX and MIN values, for which we need an XSLT equivalent to the SQL SELECT MAX() and SELECT MIN() functions.
There is a neat trick to do this which can be summed up thus:
- Sort ascending and pick the first node and you have your MIN.
- Sort descending and pick the first node and you have your MAX.
Examples of both, given the above XML are here for your reference.
Obtaining the MIN:
<!-- Create a variable named $minEventDate containing the MIN date -->
<xsl:variable name="minEventDate">
<xsl:for-each select="event">
<xsl:sort select="@date" data-type="text" order="ascending" />
<xsl:if test="position() = 1">
<xsl:value-of select="@date" />
</xsl:if>
</xsl:for-each>
</xsl:variable>
Obtaining the MAX:
<!-- Create a variable named $maxEventDate containing the MAX date -->
<xsl:variable name="maxEventDate">
<xsl:for-each select="event">
<xsl:sort select="@date" data-type="text" order="descending" />
<xsl:if test="position() = 1">
<xsl:value-of select="@date" />
</xsl:if>
</xsl:for-each>
</xsl:variable>
3 Comments, Comment or Ping
Rob Roe
That’s brilliant! Very useful, I’m suprised there are not more comments and thanks, so thank you very much for this! :)
Mar 9th, 2005
Sajesh Enampurath
Hey that one simple and useful code you have there David… It helped me a lot Thankx :). Would like to add that the line — was not working out for me. It can be substited with — The complete code is as below:
hidden
eventName
Aug 25th, 2005
prak
Thanks. Saved me a whole lot of time with this help.
Jul 26th, 2006
Reply to “XSLT Version of SQL SELECT MAX() and SELECT MIN()”