如何将列总计作为一行

时间:2016-02-19 19:47:30

标签: sql sql-server vb.net sql-server-2008

我有一个SQL查询:

Location       Net_Sales      Total Visits   AVG Money Per Visit
1               100                5                  20            
2                50                2                  25
3               200                2                  100

这是在VB.NET中运行并存储在数据表中从那里,我将其转换为HTML并作为电子邮件正文发送。

输出

Location       Net_Sales      Total Visits   AVG Money Per Visit
1               100                5                  20            
2                50                2                  25
3               200                2                  100
Total:          350                9                  38.89

我希望输出与Totals一样:

Public Function DataTableToHTMLTable(ByVal inTable As DataTable) As String
        Dim dString As New StringBuilder
        dString.Append("<table border=""1"" cellpadding=""0"" cellspacing=""0"">")
        dString.Append(GetHeader(inTable))
        dString.Append(GetBody(inTable))
        dString.Append("</table>")
        Return dString.ToString
    End Function

    Private Function GetHeader(ByVal dTable As DataTable) As String
        Dim dString As New StringBuilder

        dString.Append("<thead><tr>")
        For Each dColumn As DataColumn In dTable.Columns
            dString.AppendFormat("<th>{0}</th>", dColumn.ColumnName)
        Next
        dString.Append("</tr></thead>")

        Return dString.ToString
    End Function

    Private Function GetBody(ByVal dTable As DataTable) As String
        Dim dString As New StringBuilder

        dString.Append("<tbody>")

        For Each dRow As DataRow In dTable.Rows
            dString.Append("<tr>")
            For dCount As Integer = 0 To dTable.Columns.Count - 1
                dString.AppendFormat("<td td align='center'>{0}</td>", dRow(dCount))
            Next
            dString.Append("</tr>")
        Next
        dString.Append("</tbody>")

        Return dString.ToString()
    End Function

如何在转换为HTML之前在SQL或数据表中获取sum列。

以下是我转换为HTML的方式:

{{1}}

2 个答案:

答案 0 :(得分:1)

您可以在GROUP BY中使用WITH ROLLUP。此外,您可以在其中抛出GROUPING()来标记总数。

Select 
CASE WHEN GROUPING(Location) = 1 THEN 'Total' ELSE CAST(location AS VARCHAR(2)) END AS location
, SUM(net_sales) AS net_sales
, SUM(total_visits) AS total_visits
, CAST(AVG(Avg_money_per_visit) AS DECIMAL(10,2)) AS avg_money_per_visit
from Daily_Sales
where day = @day
Group By Location WITH ROLLUP

答案 1 :(得分:0)

假设'Location'是一个varchar字段,您可以将total字段附加到基本查询以从DB本身返回总和:

--<<Original Query>>
UNION ALL
SELECT 
    'Total:'
    , sum(net_sales)
    , sum(total_visits)
    , sum(Avg_money_per_visit)
from
    Daily_Sales