将多列WRT转换为MySQL

时间:2015-12-31 06:26:27

标签: mysql transpose

我搜索了转置和支点但却找不到这样的东西。 输入表:

+-----+-------+-------+-------+
| TID |  TP1  |  TP2  |  TP3  |
+-----+-------+-------+-------+
| A   | link1 | link1 | link3 |
| B   | link3 |       |       |
| C   | link2 |       |       |
+-----+-------+-------+-------+

必需的输出表:

+-----+--------+-------+
| TID | TP Num |  REF  |
+-----+--------+-------+
| A   |      1 | link1 |
| A   |      2 | link1 |
| A   |      3 | link3 |
| B   |      1 | link3 |
| C   |      1 | link2 |
+-----+--------+-------+

1 个答案:

答案 0 :(得分:0)

这有点复杂,您需要使用union all来获得垂直表示,然后使用用户定义的变量获取nums的内容

 dtbl = new DataTable();
 dtbl.Columns.Add("Ad.No", typeof(String)); alignment[0] = 'C'; width[1] = 40;
 dtbl.Columns.Add("AdmissionDate", typeof(String)); alignment[1] = 'C'; width[2] = 50;
 dtbl.Columns.Add("Name", typeof(String)); alignment[2] = 'L'; width[3] = 100;
 dtbl.Columns.Add("Class", typeof(String)); alignment[3] = 'C'; width[5] = 40;
 for (int i = model.FromYear; i <= model.ToYear; i++)
 {
   for (int j = model.FromMonth; j <= model.ToMonth; j++)
   {
     for (int k = model.FromDay; k <= model.ToDay; k++)
     {
       dtbl.Columns.Add(Common.CommonUtility.GetShortMonthName(j)+" "+k, typeof(String)); alignment[4] = 'C'; width[5] = 40;
     }
   }

   for (int i = model.FromYear; i <= model.ToYear; i++)
   {
     for (int j = model.FromMonth; j <= model.ToMonth; j++)
     {
       for (int k = model.FromDay; k <= model.ToDay; k++)
       {
         //  dtbl.Rows.Add(dt[j]=std.value);
         //   foreach (var r in std.value){

         dtbl.Rows.Add(dt["Ad.No"] = std.AdmissionNo, dt["AdmissionDate"] = Convert.ToDateTime(std.date.ToString()).ToString("dd/MM/yyyy"), dt["Class"] = std.Class, dt["Name"] = std.StudentName,dt[j]=std.value);
       }
     }

http://sqlfiddle.com/#!9/1d15c/14