sql-server - DatagridView 中的动态数据透视表
问题描述
我在 VB.net 中有一个项目,它将 SQL 服务器作为数据库。表名是Variation
,它有列
JobNo
VariationNo
VariationRef
Amount
我不知道一个特定的 JobNo 会有多少变化。我需要转换这个
JobNo | VariationNo | VariationRef | Amount
1000 | 1 | ABC | 10
1000 | 2 | ABD | 15
1100 | 1 | ABE | 50
1100 | 2 | ABF | 55
1100 | 3 | ABG | 60
进入这个
JobNo | V-1 | V-2 | V-3 etc.. to the last number
1000 | 10 | 15 | 0
1100 | 50 | 55 | 60
并显示它datagridview
那么我的字符串(SQLString)应该是什么?
我的代码如下
Dim con As New SqlConnection("Server=SREE-PC\SQLEXPRESS04;Database=project;Integrated security=true")
Dim SQLString As String =???
Dim cmd As New SqlCommand(SQLString, con)
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable
adapter.Fill(table)
DataGridView1.DataSource = table
解决方案
我用下面的代码得到了我想要的结果。Andrew Morton 先生在字符串连接部分帮助了我。但我觉得我的解决方案有点冗长,尤其是在开始时。有什么建议吗?
Dim SQLString1 As String = "Select STRING_AGG([VariationNo],',')Intcolumn from (select distinct variationNo from variation)tmp"
Dim cmd1 As New SqlCommand(SQLString1, con)
Dim adapter1 As New SqlDataAdapter(cmd1)
Dim table1 As New DataTable
adapter1.Fill(table1)
Dim tmplst As String = table1.Rows(0).Item("IntColumn").ToString
Dim clmName As String = "[" & tmplst.Replace(",", "],[") & "]"
Dim addvar As String = " as [Variation-" & tmplst.Replace(",", "]/ as [Variation-") & "]"
Dim tmpclmname As String = "IsNull(" & clmName.Replace(",", ",0)/IsNull(") & ",0)"
Dim joined = tmpclmname.Split({"/"c}).Zip(addvar.Split({"/"c}), Function(x, y) x & y).ToList()
Dim tmpclmname1 = String.Join(", ", joined)
Dim clmName1 As String = tmpclmname1.Replace("/", ",")
Dim SQLString As String = "Select JobNo," & clmName1 & "
from (Select JobNo,VariationNo,Amount from variation) as pivotdata
pivot
(
Max(Amount)
For VariationNo
In (" & clmName & ")
)AS Pivoting"
Dim cmd As New SqlCommand(SQLString, con)
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable
adapter.Fill(table)
DataGridView1.DataSource = table
推荐阅读
- ruby-on-rails - 在使用 Shrine 和 Rails 加密之前为图像文件设置 mime 类型
- python - 每次满足条件语句时,如何打印列表的一个(不同)部分?
- r - 如何在 rpart 回归树图中将绘制的数字从科学计数法更改为标准形式?
- c++ - C++ 动态工具提示
- javascript - 尝试返回一个新字符串,其中一些字符被其他字符替换
- qt5 - QModelIndex 创建的地点和时间
- python - 范围输出成字符串 | 错误: [
在 0x02229CA0>] - python - Python。按另一个列表中指定的随机集大小对列表进行索引
- php - 在脚本中设置 application/json 内容类型不起作用
- sql-server - 由同一用户帐户登录执行的用户连接计数