在 HTML 中使用 GROUP BY 命令时如何显示 SUM(Quantity)

How do I display SUM(Quantity) while using GROUP BY command in HTML

我能够完美地显示 ItemID 并将 ItemID 组合在一起。当我在 MS Access 中尝试 SQL 语句时,数量加起来非常好,但我无法在 HTML.

中复制它

这是代码

<%
dim Con,rs, sql

set con = server.CreateObject("ADODB.Connection")
set rs = server.CreateObject("ADODB.Recordset")

Con.Open("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=" &    Server.MapPath("Database/Name.accdb"))

sql = "SELECT ItemID, SUM(Quantity) FROM tblCreatedItems GROUP BY ItemID ORDER    BY tblCreatedItems.ItemID"

rs.open sql, Con
%>
<body>
<table width="467" align="center">
<th colspan="5"><strong>Items Sold</strong></th>
<tr>
<td width="119"><strong>ItemID</strong></td>
<td width="165"><strong>Quantity</strong></td>
</tr>
<tr>
<% while not rs.eof%>
<td><%=rs("ItemID")%></td>
<td>
<% dim sql2
set sql2=con.execute("SELECT SUM(Quantity) FROM tblCreatedItems GROUP BY ItemID ORDER BY tblCreatedItems.ItemID" )

    response.Write(sql2)
%></td>
</tr>
<% rs.movenext
wend
%>
</table>
</body>

您已经在第一个查询中按 itemid 分组,不需要第二个查询来显示总和。

在您的 sql 中,为 SUM 字段添加一个别名(引用该字段的名称):

SUM(Quantity) 更改为 SUM(Quantity) as NoOfItems(或任何您喜欢的别名)

sql 语句变为:

SELECT ItemID, SUM(Quantity) as NoOfItems 
FROM tblCreatedItems 
GROUP BY ItemID 
ORDER BY tblCreatedItems.ItemID

然后:

<td><%=rs("NoOfItems")%></td>

应该会显示您的求和字段。

因此,您的 table 代码变为:

<table width="467" align="center">
<th colspan="5"><strong>Items Sold</strong></th>
<tr>
<td width="119"><strong>ItemID</strong></td>
<td width="165"><strong>Quantity</strong></td>
</tr>
<tr>
<% while not rs.eof%>
<td><%=rs("ItemID")%></td>
<td><%=rs("NoOfItems")%></td>
</tr>
<% rs.movenext
wend
%>
</table>