4

我在我的 c# 代码中有这个数据表:

Date     | Employee | Job1 | Job2 |  Job3 |
---------|----------|------|------|-------|
1/1/2012 | A        | 1.00 | 1    |  1    |
1/1/2012 | B        | 2.5  | 2    |  2    |
1/1/2012 | C        | 2.89 | 1    |  4    |
1/1/2012 | D        | 4.11 | 2    |  1    |
1/2/2012 | A        | 3    | 2    |  5    |
1/2/2012 | B        | 2    | 2    |  2    |
1/2/2012 | C        | 3    | 3    |  3    |
1/2/2012 | D        | 1    | 1    |  1    |
1/3/2012 | A        | 5    | 5    |  5    |
1/3/2012 | B        | 2    | 2    |  6    |
1/3/2012 | C        | 1    | 1    |  1    |
1/3/2012 | D        | 2    | 3    |  4    |
2/1/2012 | A        | 2    | 2    |  2    |
2/1/2012 | B        | 5    | 5    |  2    |
2/1/2012 | D        | 2    | 2    |  2    |
2/2/2012 | A        | 3    | 3    |  3    |
2/2/2012 | B        | 2    | 3    |  3    |
3/1/2012 | A        | 4    | 4    |  2    |

现在我想创建另一个 DataTable,它看起来像这样:

Job1    
Employee | 1/1/2012 | 1/2/2012 | 1/3/2012 | 2/1/2012 | 2/2/2012 |
---------|----------|----------|----------|----------|----------|
A        | 1.00     | 3        | 5        | 2        | 3        |
B        | 2.50     | 2        | 2        | 5        | 2        |
C        | 2.89     | 3        | 1        | -        |          |
D        | 4.11     | 1        | 2        | 2        |          |
Total    | 10.50    | 9        | 10       | 9        | 5        |

请建议如何使用 Linq 和 C# 制作这个数据透视表。

4

2 回答 2

5
var query = from foo in db.Foos
            group foo by foo.Date into g
            select new {
                Date = g.Key,
                A = g.Where(x => x.Employee == "A").Sum(x => x.Job1),
                B = g.Where(x => x.Employee == "B").Sum(x => x.Job1),
                C = g.Where(x => x.Employee == "C").Sum(x => x.Job1),
                D = g.Where(x => x.Employee == "D").Sum(x => x.Job1),
                Total = g.Sum(x => x.Job1)
            };

您也可以申请OrderBy(x => x.Date)查询。

于 2013-01-24T07:00:06.887 回答
1

由于列的动态特性,您将无法使用 LINQ 执行此操作。LINQ to SQL 需要一种将结果集字段映射到属性值的静态方法。相反,您可以查看PIVOTSQL 语句并将结果填充到DataTable

http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

于 2013-01-24T07:55:29.353 回答