C# DataTable重新排列组合问题

.Net技术 码拜 9年前 (2015-11-15) 1596次浏览
已知在数据库中使用存储过程查询到如下表
C# DataTable重新排列组合问题
注意图中黄色部分的二三四列都是一样的,只是后面送货日期不一样。
要求重新组合成如下样式:
C# DataTable重新排列组合问题
可以看到,蓝色部分的两行合并了。
绿色部分添加和横向总想的求和
求实现方法或思路,假如能直接在数据库中使用存储过程完成也可以。
谢谢
解决方案:5分
完全可以在””SELECT * FROM tPo2 PIVOT (SUM(GRQty2) FOR delDate IN (“”+@sql+””)) a WHERE vendor = “”+ “”50002903″”这句sql外面再套一层用于合并的group by
解决方案:5分
存储过程里用查询拼接字符串的方法,既然你能查出后面不固定列,加group by 应该也不是难事吧?也可以处理Datatable,本人做过相似的问题,前面固定的列你可以作为分组依据嘛,可以用linq,也可以用DataTble.ToTable。然后创建另外一个相同架构Datable,即用Clone(),每一组,循环将分组键值及非固定列的值插入去
解决方案:20分
http://www.cnblogs.com/zhangzt/archive/2010/07/29/1787825.html
注意看行转列的第5个例子和之后的怎么样分组
解决方案:10分
大致写了下
结构

class Key
{
	public string vendor;
	public string purchDoc;
	public string material;
	public string shoText;
	public override int GetHashCode()
	{
		unchecked
		{
			return
				((vendor.GetHashCode() * 33 +
				purchDoc.GetHashCode()) * 33 +
				material.GetHashCode()) * 33 +
				shoText.GetHashCode();
		}
	}
	public override bool Equals(object obj)
	{
		Key other = obj as Key;
		return other != null &&
			other.vendor == this.vendor &&
			other.purchDoc == this.purchDoc &&
			other.material == this.material &&
			other.shoText == this.shoText;
	}
}
class Value
{
	public Dictionary<string, string> data;
}
Dictionary<Key, Value> table; //hashtable

转换过程

DataTable dt; //要操作的数据表
//合并过程
foreach (DataRow row in dt.Rows)
{
	Key key = new Key
	{
		vendor = (string)row["vendor"],
		purchDoc = (string)row["purchDoc"],
		material = (string)row["material"],
		shoText = (string)row["shoText"],
	};
	Value value;
	//查找
	if(!table.TryGetValue(key, out value))
	{
		value = new Value();
		table.Add(key, value);
	}
	//合并value, 5是日期开始的列号
	for (int col = 5; col < dt.Columns.Count; ++col)
	{
		if (!value.data.ContainsKey(dt.Columns[col].ColumnName) && row[col] != null)
			value.data.Add(dt.Columns[col].ColumnName, (string)row[col]);
	}
}
//写入合并后的数据
//这边可以直接写sql
foreach (var item in table)
{
	DataRow newrow = dt.NewRow();
	newrow["vender"] = item.Key.vendor;
	//...........
	foreach (var item2 in item.Value.data)
	{
		newrow[item2.Key] = item2.Value;
	}
	dt.Rows.Add(newrow);
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C# DataTable重新排列组合问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)