在sqlsugar中使用行转列 列为值类型 行里数据为该列的数据个数
在SqlSugar中,可以使用Pivot方法实现行转列,例如:
假设我们有以下数据表:
CREATE TABLE StudentScore (
Id INT PRIMARY KEY,
StudentName VARCHAR(50),
CourseName VARCHAR(50),
Score INT
);
INSERT INTO StudentScore VALUES (1, 'Tom', 'Math', 90);
INSERT INTO StudentScore VALUES (2, 'Tom', 'English', 80);
INSERT INTO StudentScore VALUES (3, 'Tom', 'Science', 70);
INSERT INTO StudentScore VALUES (4, 'Jerry', 'Math', 85);
INSERT INTO StudentScore VALUES (5, 'Jerry', 'English', 75);
INSERT INTO StudentScore VALUES (6, 'Jerry', 'Science', 65);
我们可以使用以下代码将学生的成绩转换为列:
var db = new SqlSugarClient(new ConnectionConfig {
ConnectionString = "your_connection_string",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true
});
var result = db.Queryable<StudentScore>()
.GroupBy(s => s.StudentName)
.Select(s => new {
StudentName = s.StudentName,
Math = SqlFunc.AggregateCount(s.CourseName == "Math" ? s.Score : null),
English = SqlFunc.AggregateCount(s.CourseName == "English" ? s.Score : null),
Science = SqlFunc.AggregateCount(s.CourseName == "Science" ? s.Score : null)
})
.ToList();
这里使用了SqlFunc.AggregateCount方法来统计每个课程的成绩个数,如果该行不属于该课程,则传入null。
最终的结果将会是:
[
{ StudentName = "Tom", Math = 1, English = 1, Science = 1 },
{ StudentName = "Jerry", Math = 1, English = 1, Science = 1 }
]
其中,每一行代表一个学生,每一列代表一门课程的成绩个数
原文地址: http://www.cveoy.top/t/topic/hwse 著作权归作者所有。请勿转载和采集!