用ROLLUP進行分類資料統計(二)

來源:互聯網
上載者:User

我們介紹了ms sql server中的roll up語句。下面開始介紹如何用datagrid結合rollup語句來進行分類統計。

我們要達到的效果是這樣的:

首先,應先將資料庫中的產品資料按照所屬的不同的目錄列舉出來,這其中要用到一些技巧.這裡先用SQL語句,從資料庫讀取product表的資料,之後放到dataset的預設datatable中去,然後檢查每一個產品所屬的類別,如果發現某一個產品的類別和前一條記錄中產品所屬的類別不一樣的話,那麼就可以肯定當前產品是屬於一個新的分類了,就可以插入新的行,並且加以修飾,成為分類標題,同時將roll up的統計結果顯示在相應的位置就可以了。我們先來看page_load部分的代碼

Sub Page_Load(Sender As Object, E As EventArgs) Handles MyBase.Load
  ' TODO: Update the ConnectionString and CommandText values for your application
dim ConnectionString as string = "server=localhost;database=northwind;UID=sa"
  Dim CommandText As String = "Select CASE WHEN (Grouping(CategoryName)=1) THEN " & _
       "'MainTotal' ELSE categoryname END AS CategoryName, "
  CommandText &= " CASE WHEN (Grouping(ProductName)=1) THEN 'SubTotal' ELSE " & _
       "Productname END AS ProductName,"
  CommandText &= " Sum(UnitPrice) as unitprice, "
  CommandText &= " Sum(UnitsinStock) as UnitsinStock "
  CommandText &= " from Products INNER JOIN Categories On Products.categoryID = " & _
          " Categories.CategoryID"
  CommandText &= " Group By Categoryname, ProductName WITh ROLLUP "
  Dim myConnection As New SqlConnection(ConnectionString)
  Dim myCommand As New SqlDataAdapter(CommandText, myConnection)
  Dim ds As New DataSet
  myCommand.Fill(ds)
  Dim curCat As String ‘指示目前記錄中產品所屬的類別
  Dim prevCat As String ‘指示上一條記錄中產品所屬的類別
  Dim i As Integer = 0  ‘要插入分類標題列的位置,用I表示
'遍曆結果集,找出要插入分類標題的行
  Do While i <= ds.Tables(0).Rows.Count - 1
    curCat = ds.Tables(0).Rows(i).Item(0)
    If curCat <> prevCat Then ‘如果發現前後兩記錄的所屬類別不一樣
      prevCat = curCat
      Dim shRow As DataRow = ds.Tables(0).NewRow
      shRow(1) = ds.Tables(0).Rows(i).Item(0)
      
      'Change ItemDataBound marker to Negative Number
      shRow(2) = -1 ‘‘設定一個臨時的標記
        ds.Tables(0).Rows.InsertAt(shRow, i)
           i += 1
    End If
       i += 1
   Loop
  ‘將最後一行的標題改為total
  ds.Tables(0).Rows(ds.Tables(0).Rows.Count - 1).Item(1) = "Total"
  DataGrid1.DataSource = ds
  DataGrid1.DataBind()
End Sub

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.