我在VB.net中有一个项目,该项目具有SQL Server作为数据库。表名称为Variation
,它具有列
工作编号
VariationNo
VariationRef
金额
我不知道特定的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
答案 0 :(得分:0)
我用下面的代码得到了想要的结果。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