PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 4, 2022

[FIXED] How to get difference each record value from previous record

 November 04, 2022     c#, entity-framework, lambda, linq, linq-to-entities     No comments   

Issue

Please consider this Table:

Year     Month    Code     Value
--------------------------------
2011      1         1       100
2011      2         1       200
2011      3         1       250
2011      1         2       70
2011      2         2       50
2011      3         2       80

I want to achieve this result:

Code    FromYearMonth      ToYearMonth    Difference
----------------------------------------------------
 1       2011-1               2011-2        100   <----200 - 100
 1       2011-2               2011-3        50    <----250 - 200
 2       2011-1               2011-2        -20   <----50 - 70
 2       2011-2               2011-3        30    <----80 - 50

How can I create this result with LINQ. Thanks


Solution

You need to join datasource with itself to get all pairs of (monthStart, monthEnd) records, then calculate difference:

from monthStart in dataSource
join monthEnd in dataSource
on new { monthStart.Code, date = monthStart.Year * 12 + monthStart.Month }
equals new { monthEnd.Code, date = monthEnd.Year * 12 + monthEnd.Month - 1}
select new {
  monthStart.Code,
  FromYear = monthStart.Year,
  FromMonth = monthStart.Month,
  ToYear = monthEnd.Year,
  ToMonth = monthEnd.Month,
  Difference = monthEnd.Value - monthStart.Value
}


Answered By - pakeha_by
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing