前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SQL 转 Linq 备忘录

SQL 转 Linq 备忘录

原创
作者头像
谭广健
修改2019-01-21 15:01:30
6870
修改2019-01-21 15:01:30
举报
文章被收录于专栏:谭广健的专栏谭广健的专栏

写SQL的分组统计合作等基本没啥问题,随便出手都解决,但最近用MVC5 写了一个项目,其中的查询统计就不这么容易,因为用了EF进行数据连接处理,所有条件都用linq,当然更重要的是懒得加SQL的调用方法.而LING的统计说难也不难,说易也不易.本来写个12个月的累计合加,,简单地用SQL写了一下

"select state,

sum(case month(submdate) when 1 then 1 else 0 end) as "1",

sum(case month(submdate) when 2 then 1 else 0 end) as "2",

sum(case month(submdate) when 3 then 1 else 0 end) as "3",

sum(case month(submdate) when 4 then 1 else 0 end) as "4",

sum(case month(submdate) when 5 then 1 else 0 end) as "5",

sum(case month(submdate) when 6 then 1 else 0 end) as "6",

sum(case month(submdate) when 7 then 1 else 0 end) as "7",

sum(case month(submdate) when 8 then 1 else 0 end) as "8",

sum(case month(submdate) when 9 then 1 else 0 end) as "9",

sum(case month(submdate) when 10 then 1 else 0 end) as "10",

sum(case month(submdate) when 11 then 1 else 0 end) as "11",

sum(case month(submdate) when 12 then 1 else 0 end) as "12"

from K_WebOrderList where year(submdate)=year(getdate()) group by state"

就这句,咋换好呢?想了N多方法,最后是这样解决:

var K_List = K_WebOrderList.GetListBy(a => a.submdate.Value.Year.ToString() == "2019")

.GroupBy(t=>t.state)

.Select(a => new {

state= a.Key,

Jan = a.Sum(item=>item.submdate.Value.Month == 1 ? 1 :0),

Feb = a.Sum(item => item.submdate.Value.Month == 2 ? 1 : 0),

Mar = a.Sum(item => item.submdate.Value.Month == 3 ? 1 : 0),

Apr = a.Sum(item => item.submdate.Value.Month == 4 ? 1 : 0),

May = a.Sum(item => item.submdate.Value.Month == 5 ? 1 : 0),

Jun = a.Sum(item => item.submdate.Value.Month == 6 ? 1 : 0),

Jul = a.Sum(item => item.submdate.Value.Month == 7 ? 1 : 0),

Aug = a.Sum(item => item.submdate.Value.Month == 8 ? 1 : 0),

Sep = a.Sum(item => item.submdate.Value.Month == 9 ? 1 : 0),

Oct = a.Sum(item => item.submdate.Value.Month == 10 ? 1 : 0),

Nov = a.Sum(item => item.submdate.Value.Month == 11 ? 1 : 0),

Dec = a.Sum(item => item.submdate.Value.Month == 12 ? 1 : 0)

}).ToList();

哈哈,感觉头上又有些光环了,当然可以更好,不会现在算抛个砖吧.有更好的可以留言.

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档