Search code examples
asp-classic

Result like a group with Classic ASP


I have a table (MSSQL) with data like:

1   AAA 100
2   BBB 101
3   C   100
4   D   100

I would like to list itens like:

100:
- 1 AAA
- 3 C
- 4 D

101:
- 2 BBB

How can I do this? I have done a While inside a While but the result isn't what I am waiting:

<%
    Set Group= TarefasConexaoMSSQL.Execute("SELECT DISTINCT GroupName FROM _NewDummy")
    GroupName= Group("GroupName")
    WHILE NOT Group.EOF
%>

<p>
    <a href="#"><% Response.Write Group("GroupName") %></a>
</p>
<%
    Set Itens= TarefasConexaoMSSQL.Execute("SELECT * FROM _NewDummy WHERE GroupName= '"& GroupName &"'")
    One= Itens("One")
    Two= Itens("Two")
%>
    <%
        WHILE NOT Itens.EOF
    %>

    - One: <% Response.Write One %>
    - Two: <% Response.Write Two %>

    <%
        Itens.MOVENEXT
        WEND
    %>
<%
    Group.MOVENEXT
    WEND
%>

Thanks for any info on this.


Solution

  • You don't need any nested loop here, just sort by the group name and keep track of the previous value vs. the current value. When the value changes (or first value) show the group name.

    Code:

    <%
    Set oRS= TarefasConexaoMSSQL.Execute("SELECT * FROM _NewDummy ORDER BY GroupName ASC")
    Dim currentGroupName, previousGroupName
    currentGroupName = ""
    previousGroupName = ""
    Do Until oRS.EOF
        currentGroupName = oRS("GroupName")
        One = oRS("One")
        Two = oRS("Two")
        If currentGroupName<>previousGroupName Then
            Response.Write("<p>")
            Response.Write("<a href="#">" & currentGroupName & "</a>")
            Response.Write("</p>")
        End If
        Response.Write("- One: " & One & ", Two: " & Two & "<br />")
        previousGroupName = currentGroupName
        oRS.MoveNext
    Loop
    oRS.Close
    %>