我有一个T-SQL 2005查询返回:
pid propertyid displayname value ----------- ----------- --------------- --------------- 14270790 74 Low Price 1.3614 14270790 75 High Price 0 14270791 74 Low Price 1.3525 14270791 75 High Price 0 14270792 74 Low Price 1.353 14270792 75 High Price 0 14270793 74 Low Price 1.3625 14270793 75 High Price 0 14270794 74 Low Price 1.3524 14270794 75 High Price 0
我想做的主要是在displayname
球场上转移,希望产生:
pid Low Price High Price 14270790 1.3614 0 14270791 1.3525 0 14270792 1.353 0 14270793 1.3625 0 14270794 1.3524 0
(不确定如何输出propertyid字段,所以我把它遗漏了(希望它只是与低价和高价字段并排,以表明它们的ID,但我认为这不会起作用.)
问题是,原来的内容displayname
领域是动态的-它是从一个与联接生产PropertyName' table, so the number of pivoted columns is variable. It could therefore contain
高价格,
低价格,
打开and
Close`,这取决于与该表返回加入.
这是当然的,相对容易(无论我在写初始查询的麻烦!)在一个固定的查询或存储过程来产生这种转动.但是,是有可能得到LINQ生成的SQL查询这将名字而产生的每一列不必编写动态(可能在一个存储过程)查询,其中列出了列名?
谢谢,
马特.
我会给你一个带有不同数据的样本(我需要的).您可以根据需要进行调整.请注意,只使用了两个linq查询,其他大部分都是将列表转换为数据表.
var data = new[] { new{Student=1, Subject="English", Marks=40}, new{Student=1, Subject="Maths", Marks=50}, new{Student=1, Subject="Science", Marks=60}, new{Student=1, Subject="Physics", Marks=70}, new{Student=1, Subject="Chemistry", Marks=80}, new{Student=1, Subject="Biology", Marks=90}, new{Student=2, Subject="English", Marks=4}, new{Student=2, Subject="Maths", Marks=5}, new{Student=2, Subject="Science", Marks=6}, new{Student=2, Subject="Physics", Marks=7}, new{Student=2, Subject="Chemistry", Marks=8}, new{Student=2, Subject="Biology", Marks=9} }; /*Here the pivot column is the subject and the static column is student group the data against the static column(s)*/ var groups = from d in data group d by d.Student into grp select new { StudentId = grp.Key, Marks = grp.Select(d2 => new { d2.Subject, d2.Marks }).ToArray() }; /*get all possible subjects into a separate group*/ var subjects = (from d in data select d.Subject).Distinct(); DataTable dt = new DataTable(); /*for static cols*/ dt.Columns.Add("STUDENT_ID"); /*for dynamic cols*/ foreach (var subject in subjects) { dt.Columns.Add(subject.ToString()); } /*pivot the data into a new datatable*/ foreach (var g in groups) { DataRow dr = dt.NewRow(); dr["STUDENT_ID"] = g.StudentId; foreach (var mark in g.Marks) { dr[mark.Subject] = mark.Marks; } dt.Rows.Add(dr); }