如何在linq中按月选择和分组?

时间:2015-08-03 07:23:03

标签: sql .net linq

SELECT 
    NAME, 
    M1 = SUM(CASE WHEN MONTH(PAY_DATE) = 1 THEN 1 ELSE 0 END),
    M2 = SUM(CASE WHEN MONTH(PAY_DATE) = 2 THEN 1 ELSE 0 END),
    M3 = SUM(CASE WHEN MONTH(PAY_DATE) = 3 THEN 1 ELSE 0 END),
    M4 = SUM(CASE WHEN MONTH(PAY_DATE) = 4 THEN 1 ELSE 0 END),
    M5 = SUM(CASE WHEN MONTH(PAY_DATE) = 5 THEN 1 ELSE 0 END),
    M6 = SUM(CASE WHEN MONTH(PAY_DATE) = 6 THEN 1 ELSE 0 END),
    M7 = SUM(CASE WHEN MONTH(PAY_DATE) = 7 THEN 1 ELSE 0 END)
    FROM TBL_POST 
WHERE YEAR(DATE) = 2015
GROUP BY NAME
NAME  M1    M2     M3   M4    M5     M6     M7
A     0     0      0    0     0      174    327
B     44071 50101  5501 569   65831  6998   69305
C     0     0      0    0     5      147    195
D     3438  6003   8640 8930  11598  13731  13368
E     0     1      3    2     3      3      3
F     2455  29084  993  6310  7561   19040  25722

1 个答案:

答案 0 :(得分:0)

尝试此查询

var sums = from d in Contex.TBL_POST 
where d.DATE.Value.Year=2015
group d by new {d.Name} into g
select new
{
    Name = g.Key,
    M1 = g.Sum(s => s.PAY_DATE.Value.Month==1??1:0), 
    M2 = g.Sum(s => s.PAY_DATE.Value.Month==2??1:0), 
    M3 = g.Sum(s => s.PAY_DATE.Value.Month==3??1:0), 
    M4 = g.Sum(s => s.PAY_DATE.Value.Month==4??1:0), 
    M5 = g.Sum(s => s.PAY_DATE.Value.Month==5??1:0), 
    M6 = g.Sum(s => s.PAY_DATE.Value.Month==6??1:0), 
    M7 = g.Sum(s => s.PAY_DATE.Value.Month==7??1:0) 

};