我们可以将行数转移到多列,即
checkedRows.Cast<DataGridViewRow>().GroupBy(item => item.Cells[Feature Name].Value)
.Select(group => new { FeatureName = group.Key, Properties = group.Cells["Property Name].Value.ToList() })
.ToList()
http://sqlfiddle.com/#!6/d4eb9
或任何其他方式。大多数记录(p_id)将具有固定数量的列(自定义名称)标题 - 少数几个,一些没有。非常感谢
答案 0 :(得分:2)
试试这个。我建议你自己阅读一些支点,因为它们有点时髦。您可以在此处执行此操作:https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
您会注意到的一件事是我将所有列合并为单个数据类型(字符串),因为尝试跨多个列进行操作是一场噩梦。如果您仍然需要强制执行数据类型,我会在最终选择中执行此操作。
select
p_id,
DepartmentCode = cast(DepartmentCode as varchar(30)),
Year = cast(Year as int),
StartDate = cast(StartDate as datetime),
EmpId = cast(EmpId as int),
EmpTitle = cast(EmpTitle as varchar(30))
from (select
P_ID,
custom_name,
Value = coalesce(text_value, cast(number_value as varchar(30)), convert(varchar(30), datetime, 120))
from #Temp_Trans) s
pivot(max(Value) for custom_name in (DepartmentCode, Year, StartDate, EmpID,EmpTitle))p
如果由于某种原因你很想转动多个列,你将不得不做多个支点。
答案 1 :(得分:2)
两个快速选项:
1)条件聚合
select P_ID
,DepartmentCode = max(case when Custom_Name='DepartmentCode' then Text_Value end)
,Year = max(case when Custom_Name='Year' then Text_Value end)
,StartDate = max(case when Custom_Name='StartDate' then DateTime end)
,EmpID = max(case when Custom_Name='EmpID' then Number_Value end)
,EmpTitle = max(case when Custom_Name='EmpTitle' then Text_Value end)
from #Temp_Trans
Group By P_ID
2)动态数据透视
Declare @SQL varchar(max)
Select @SQL = Stuff((Select Distinct ',' + QuoteName(Custom_Name) From #Temp_Trans For XML Path('')),1,1,'')
Select @SQL = 'Select P_ID,' + @SQL + '
From (
Select P_ID
,ITEM = Custom_Name
,Value = concat(Text_Value,Number_Value,format(DateTime,''yyyy-MM-dd''))
From #Temp_Trans
) A
Pivot (max(Value) For Item in (' + @SQL + ') ) p'
Exec(@SQL);