I'm not sure from your description exactly what output you want.
Don't think in terms of looping and conditionals. That's procedural thinking.
This is a grouping problem. In XSLT 2.0 it's something like
<xsl:for-each-group select="Value" group-adjacent="@D3">
<td>... output an item in this group
In 1.0 you use the same kind of logic but you have to identify the group boundaries by hand:
<xsl:for-each select="Value[not(@D3 = preceding-sibling::Value/@D3">
<xsl:for-each select=". | following-sibling::Value[position() < 4">
... output an item in this group
Author, XSLT Programmer's Reference and XPath 2.0 Programmer's Reference