当前位置:  开发笔记 > 后端 > 正文

LINQ的SQL命令(旋转)

如何解决《LINQ的SQL命令(旋转)》经验,为你挑选了1个好方法。

我从MySQL(使用ODBC)到MS SQL数据库的移动,我想"翻译" SQL查询LINQ.有人可以帮我这个(它应该为每个位置的SUM Charge列和几个月的组结果):

SELECT
sum(case when Location="Location1" then Charge else 0 end) as Location1,
sum(case when Location="Location2" then Charge else 0 end) as Location2,
sum(case when Location="Location3" then Charge else 0 end) as Location3,
MAKEDATE(YEAR(OrderTime),DAYOFYEAR(OrderTime)) AS date FROM Sales
GROUP BY YEAR(OrderTime),MONTH(OrderTime)
ORDER BY OrderTime DESC 

输出应如下所示:

Location1 | Location2 | Location3 | date

编辑:

我试着从这里使用LINQ示例:

是否可以使用LINQ旋转数据?

var query = context.log_sales
                            .GroupBy(c => c.OrderTime)
                            .Select(g => new
                            {
                                Date = g.Key,
                                Location1 = g.Where(c => c.Location == "Location1").Sum(c => c.Charge) ?? 0,
                                Location2 = g.Where(c => c.Location == "Location2").Sum(c => c.Charge) ?? 0
                            }).ToList();

这几乎是我的需要.应该按年分组,我不知道该怎么做.



1> Amy B..:

这可能有所帮助.

context.log_sales
.GroupBy(s => new {Year = OrderTime.Year, Month = OrderTime.Month})
.Select
( g => new {
  Date = new DateTime(g.Key.Year, g.Key.Month, 1),
  Location1 = g.Where(s => s.Location == "Location1").Sum(s => s.Charge),
  Location2 = g.Where(s => s.Location == "Location2").Sum(s => s.Charge),
  Location3 = g.Where(s => s.Location == "Location3").Sum(s => s.Charge),
  }
)
.OrderBy(x => x.Date);

推荐阅读
php
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有