你的位置:首页 > 数据库

[数据库]代码实现SQL Server动态行转列,不用存储过程


分两步查询,第一步查询出动态列,第二步使用PIVOT函数。

代码:

List<DataTable> dataTableList = new List<DataTable>();#region 指标DataTable dtEvaItemTitle = db.RunTable<Edu_EvaluationRecord>(string.Format(@"  select distinct eva.id, eva.name   from Edu_EvaluationRecord r  left join Edu_QnVolume v on r.queryid=v.id  left join Sys_EvaluationItem eva on r.evaitemid=eva.id  where v.id={0}  order by eva.id", volumeEva.Id));List<string> evaItemTitleList = new List<string>();for (int i = 0; i < dtEvaItemTitle.Rows.Count; i++){  evaItemTitleList.Add(string.Format("[{0}]", dtEvaItemTitle.Rows[i]["name"].ToString()));}string evaItemTitles = String.Join(",", evaItemTitleList.ToArray());string sql = string.Format(@"  select * from  (select stu.name as 姓名,stu.StuNum as 学号,stu.ExamNum as 考号,  case when stu.Sex='1' then '男' else '女' end as 姓别,  case when stu.Brothers='1' then '否' else '是' end as 是否独生,  stu.EduF as 父亲文化,stu.EduM as 母亲文化,  r.score as 分数,eva.Name as 题目  from Edu_EvaluationRecord r  left join Edu_Student stu on r.userid=stu.id  left join Sys_User u on stu.userid=u.id  left join Edu_QnVolume v on r.queryid=v.id  left join Sys_EvaluationItem eva on r.evaitemid=eva.id  where v.id={0}) p  pivot (sum(分数) for 题目 in ({1}))  as pvt", volumeEva.Id, evaItemTitles);DataTable dt = db.RunTable<Edu_EvaluationRecord>(sql);dt.TableName = volumeEva.Name;dataTableList.Add(dt);#endregion#region 普通DataTable dtItemTitle = db.RunTable<Edu_EvaluationRecord>(string.Format(@"  select distinct s.id, s.title   from edu_qnanswer ans  left join Edu_QnSubject s on s.id=ans.subjectid  left join Edu_QnVolume v on s.volumeid=v.id  where v.id={0}  order by s.id", volumeGeneral.Id));List<string> itemTitleList = new List<string>();for (int i = 0; i < dtItemTitle.Rows.Count; i++){  itemTitleList.Add(string.Format("[{0}]", dtItemTitle.Rows[i]["title"].ToString()));}string itemTitles = String.Join(",", itemTitleList.ToArray());sql = string.Format(@"  select * from  (select stu.name as 姓名,stu.StuNum as 学号,stu.ExamNum as 考号,  case when stu.Sex='1' then '男' else '女' end as 姓别,  case when stu.Brothers='1' then '否' else '是' end as 是否独生,  stu.EduF as 父亲文化,stu.EduM as 母亲文化,  ans.Answercontent as 选项,s.Title as 题目  from edu_qnanswer ans  left join Sys_User u on ans.answerid=u.id  left join Edu_Student stu on stu.userid=u.id  left join Edu_QnSubject s on s.id=ans.subjectid  left join Edu_QnVolume v on s.volumeid=v.id  where v.id={0}) p  pivot (max(选项) for 题目 in ({1}))  as pvt", volumeGeneral.Id, itemTitles);dt = db.RunTable<Edu_EvaluationRecord>(sql);dt.TableName = volumeGeneral.Name;dataTableList.Add(dt);#endregion

View Code