How to Calculate Employment Experience with Special CaseHow does database indexing work?How can I prevent SQL injection in PHP?How do I perform an IF…THEN in an SQL SELECT?How to return only the Date from a SQL Server DateTime datatypeHow to check if a column exists in a SQL Server table?How to concatenate text from multiple rows into a single text string in SQL server?How can I do an UPDATE statement with JOIN in SQL?How do I UPDATE from a SELECT in SQL Server?How to Delete using INNER JOIN with SQL Server?How to import an SQL file using the command line in MySQL?

Why did Robert F. Kennedy loathe Lyndon B. Johnson?

Who goes first? Person disembarking bus or the bicycle?

Computer name naming convention for security

Is homosexuality or bisexuality allowed for women?

Where are the Wazirs?

stuck in/at beta

Array or vector? Two dimensional array or matrix?

Can one block with a protection from color creature?

Is there a method for differentiating informative comments from commented out code?

Was it ever illegal to name a pig "Napoleon" in France?

What's the adjective used to qualify a software that's available on your first boot?

Is there a formal/better word than "skyrocket" for the given context?

How was the website able to tell my credit card was wrong before it processed it?

Would denouncing cheaters from an exam make me less likely to receive penalties?

What is the relationship between external and internal composition in a cartesian closed category?

How to use Adostop Eco stop bath?

Tikz people in diagram

What kind of Chinook helicopter/airplane hybrid is this?

How do I talk to my wife about unrealistic expectations?

What was the profession 芸者 (female entertainer) called in Russia?

Did depressed people far more accurately estimate how many monsters they killed in a video game?

Redirecting stderr using exec

How do ballistic trajectories work in a ring world?

Decrease spacing between a bullet point and its subbullet point



How to Calculate Employment Experience with Special Case


How does database indexing work?How can I prevent SQL injection in PHP?How do I perform an IF…THEN in an SQL SELECT?How to return only the Date from a SQL Server DateTime datatypeHow to check if a column exists in a SQL Server table?How to concatenate text from multiple rows into a single text string in SQL server?How can I do an UPDATE statement with JOIN in SQL?How do I UPDATE from a SELECT in SQL Server?How to Delete using INNER JOIN with SQL Server?How to import an SQL file using the command line in MySQL?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I am trying to calculate the years of experience



Let's say someone has multiple employments as follow:



startdate enddate
2007-08-27 2008-05-09
2007-08-27 2008-05-09
2012-01-01 2018-07-31
2013-01-06 2019-03-25


What would be the correct sql syntax to just select startdate, enddate which will be later pluged in a function to calculate the number of days for each employment?



Here's my expected result:



1st row: startdate 8/27/2007, enddate 5/9/2008 
2nd row: startdate 1/1/2012, enddate 3/25/2019


The second employment took place during the same time for the 1st employment so, it will not be counted. The fourth employment started before the third employment ended so we should use the startdate for the third employment and enddate for the fourth employment










share|improve this question
























  • All of these records are about one person? If yes, why you have duplicated rows?

    – Siamak Ferdos
    Mar 25 at 22:50












  • Does it matter for the total if date ranges overlap, or have duplicates? You could include the result you expect from the sample data.

    – LukStorms
    Mar 25 at 22:52












  • @LukStorms yes it does matter. as you see the first and the second employments started at the first time so, they should be counted only once which will total in 259 days of employments. Third and fourth employments should total in 2640 days.

    – Faris Ahmed
    Mar 25 at 22:58












  • @SiamakFerdos yes. this person has 4 part time jobs. first and second employments are two different jobs.

    – Faris Ahmed
    Mar 25 at 22:59











  • In this case there is not a single startdate and a single enddate. So what do you expect the solution to return?

    – forpas
    Mar 25 at 23:26

















0















I am trying to calculate the years of experience



Let's say someone has multiple employments as follow:



startdate enddate
2007-08-27 2008-05-09
2007-08-27 2008-05-09
2012-01-01 2018-07-31
2013-01-06 2019-03-25


What would be the correct sql syntax to just select startdate, enddate which will be later pluged in a function to calculate the number of days for each employment?



Here's my expected result:



1st row: startdate 8/27/2007, enddate 5/9/2008 
2nd row: startdate 1/1/2012, enddate 3/25/2019


The second employment took place during the same time for the 1st employment so, it will not be counted. The fourth employment started before the third employment ended so we should use the startdate for the third employment and enddate for the fourth employment










share|improve this question
























  • All of these records are about one person? If yes, why you have duplicated rows?

    – Siamak Ferdos
    Mar 25 at 22:50












  • Does it matter for the total if date ranges overlap, or have duplicates? You could include the result you expect from the sample data.

    – LukStorms
    Mar 25 at 22:52












  • @LukStorms yes it does matter. as you see the first and the second employments started at the first time so, they should be counted only once which will total in 259 days of employments. Third and fourth employments should total in 2640 days.

    – Faris Ahmed
    Mar 25 at 22:58












  • @SiamakFerdos yes. this person has 4 part time jobs. first and second employments are two different jobs.

    – Faris Ahmed
    Mar 25 at 22:59











  • In this case there is not a single startdate and a single enddate. So what do you expect the solution to return?

    – forpas
    Mar 25 at 23:26













0












0








0








I am trying to calculate the years of experience



Let's say someone has multiple employments as follow:



startdate enddate
2007-08-27 2008-05-09
2007-08-27 2008-05-09
2012-01-01 2018-07-31
2013-01-06 2019-03-25


What would be the correct sql syntax to just select startdate, enddate which will be later pluged in a function to calculate the number of days for each employment?



Here's my expected result:



1st row: startdate 8/27/2007, enddate 5/9/2008 
2nd row: startdate 1/1/2012, enddate 3/25/2019


The second employment took place during the same time for the 1st employment so, it will not be counted. The fourth employment started before the third employment ended so we should use the startdate for the third employment and enddate for the fourth employment










share|improve this question
















I am trying to calculate the years of experience



Let's say someone has multiple employments as follow:



startdate enddate
2007-08-27 2008-05-09
2007-08-27 2008-05-09
2012-01-01 2018-07-31
2013-01-06 2019-03-25


What would be the correct sql syntax to just select startdate, enddate which will be later pluged in a function to calculate the number of days for each employment?



Here's my expected result:



1st row: startdate 8/27/2007, enddate 5/9/2008 
2nd row: startdate 1/1/2012, enddate 3/25/2019


The second employment took place during the same time for the 1st employment so, it will not be counted. The fourth employment started before the third employment ended so we should use the startdate for the third employment and enddate for the fourth employment







sql sql-server






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 3 at 3:18









Dale Burrell

4,1095 gold badges27 silver badges56 bronze badges




4,1095 gold badges27 silver badges56 bronze badges










asked Mar 25 at 22:32









Faris AhmedFaris Ahmed

44 bronze badges




44 bronze badges












  • All of these records are about one person? If yes, why you have duplicated rows?

    – Siamak Ferdos
    Mar 25 at 22:50












  • Does it matter for the total if date ranges overlap, or have duplicates? You could include the result you expect from the sample data.

    – LukStorms
    Mar 25 at 22:52












  • @LukStorms yes it does matter. as you see the first and the second employments started at the first time so, they should be counted only once which will total in 259 days of employments. Third and fourth employments should total in 2640 days.

    – Faris Ahmed
    Mar 25 at 22:58












  • @SiamakFerdos yes. this person has 4 part time jobs. first and second employments are two different jobs.

    – Faris Ahmed
    Mar 25 at 22:59











  • In this case there is not a single startdate and a single enddate. So what do you expect the solution to return?

    – forpas
    Mar 25 at 23:26

















  • All of these records are about one person? If yes, why you have duplicated rows?

    – Siamak Ferdos
    Mar 25 at 22:50












  • Does it matter for the total if date ranges overlap, or have duplicates? You could include the result you expect from the sample data.

    – LukStorms
    Mar 25 at 22:52












  • @LukStorms yes it does matter. as you see the first and the second employments started at the first time so, they should be counted only once which will total in 259 days of employments. Third and fourth employments should total in 2640 days.

    – Faris Ahmed
    Mar 25 at 22:58












  • @SiamakFerdos yes. this person has 4 part time jobs. first and second employments are two different jobs.

    – Faris Ahmed
    Mar 25 at 22:59











  • In this case there is not a single startdate and a single enddate. So what do you expect the solution to return?

    – forpas
    Mar 25 at 23:26
















All of these records are about one person? If yes, why you have duplicated rows?

– Siamak Ferdos
Mar 25 at 22:50






All of these records are about one person? If yes, why you have duplicated rows?

– Siamak Ferdos
Mar 25 at 22:50














Does it matter for the total if date ranges overlap, or have duplicates? You could include the result you expect from the sample data.

– LukStorms
Mar 25 at 22:52






Does it matter for the total if date ranges overlap, or have duplicates? You could include the result you expect from the sample data.

– LukStorms
Mar 25 at 22:52














@LukStorms yes it does matter. as you see the first and the second employments started at the first time so, they should be counted only once which will total in 259 days of employments. Third and fourth employments should total in 2640 days.

– Faris Ahmed
Mar 25 at 22:58






@LukStorms yes it does matter. as you see the first and the second employments started at the first time so, they should be counted only once which will total in 259 days of employments. Third and fourth employments should total in 2640 days.

– Faris Ahmed
Mar 25 at 22:58














@SiamakFerdos yes. this person has 4 part time jobs. first and second employments are two different jobs.

– Faris Ahmed
Mar 25 at 22:59





@SiamakFerdos yes. this person has 4 part time jobs. first and second employments are two different jobs.

– Faris Ahmed
Mar 25 at 22:59













In this case there is not a single startdate and a single enddate. So what do you expect the solution to return?

– forpas
Mar 25 at 23:26





In this case there is not a single startdate and a single enddate. So what do you expect the solution to return?

– forpas
Mar 25 at 23:26












4 Answers
4






active

oldest

votes


















0














Use Distinct to remove dplicated records. Then you can use this query:



Select totaldays / 365 from 
(Select Sum(
DATEDIFF(day, srartdate, enddate )
) As totaldays
)





share|improve this answer

























  • thanks for the help but, this's not what I'm looking for. as I mentioned there's a function that has some special logic which takes the startdate and enddate as parameters. I just need help figuiring out the correct way to select the startdate, enddate. my expected outpout would be: 1st row: startdate 8/27/2007, enddate 5/9/2008 2nd row: startdate 1/1/2012, enddate 3/25/2019

    – Faris Ahmed
    Mar 25 at 23:23












  • You can nothave unique startdate and enddate. You should calc them record by record which is not important they making via function or using in a function , ... . Otherwise complete your question with ur logics and function and expected resuls

    – Siamak Ferdos
    Mar 25 at 23:30


















0














This query returns the dates without overlapping:



select 
v.startdate startdate,
min(vv.enddate) enddate
from view_appemployment v
inner join view_appemployment vv
on v.startdate <= vv.enddate
and not exists (
select * from view_appemployment vvv
where vv.enddate >= vvv.startdate and vv.enddate < vvv.enddate
)
where not exists (
select * from view_appemployment vvvv
where v.startdate > vvvv.startdate and v.startdate <= vvvv.enddate
)
group by v.startdate


See the demo

Results:



startdate | enddate 
------------------ | ------------------
27/08/2007 00:00:00 | 09/05/2008 00:00:00
01/01/2012 00:00:00 | 25/03/2019 00:00:00





share|improve this answer























  • it will take me sometime to process the logic you wrote but, not sure why I'm not getting any data back when I specify the id for that user. so if I add AND UserID = 100 I don't get any data back.

    – Faris Ahmed
    Mar 25 at 23:54











  • This code assumes operates on view_appemployment. So if you want a where id = ? it must be plugged in every occurrence of view_appemployment, like: select * from view_appemployment where id = ?

    – forpas
    Mar 25 at 23:59











  • Got it. In which part should I add the ISNULL check to replace the enddate with getdate(). actually the way I have the data set up is the fourth employment has no enddate. in this case it should be replaced with today's date

    – Faris Ahmed
    Mar 26 at 0:04











  • Everywhere you see enddate you must do: coalesce(enddate, CONVERT (date, GETDATE()))

    – forpas
    Mar 26 at 0:09











  • Got it. how would i incroporate this part which was part of the original query I used in the past: Age18 is selecting the user date of birth from another table. and ( (StartDate >= Age18) OR (StartDate < Age18 --Individual started position before becoming 18 AND (EndDate > Age18 OR EndDate IS NULL) --position ended after he trurned 18 or still working at same position AND DATEDIFF(YYYY,App.BirthDate, GETDATE()) > 18) -- Individual is now 18 years old )

    – Faris Ahmed
    Mar 26 at 0:23



















0














Please try this:



RESULT PIC



SELECT concat(id," row: start date ",date_format(start_date,'%d/%m/%y')," end date ",date_format(end_date,'%d/%m/%y'))as dateinfo FROM `dates`





share|improve this answer










New contributor



shaik sazeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


























    0














    This is a Gaps & Islands in Sequences problem, the following query should do what you want:



    CREATE TABLE #emp (empid int, startdate date,enddate date)
    INSERT INTO #emp VALUES
    (1,'2007-08-27','2008-05-09'),
    (1,'2007-08-27','2008-05-09'),
    (1,'2012-01-01','2018-07-31'),
    (1,'2013-01-06','2019-03-25')

    ;WITH starts AS (
    SELECT em.*,
    (CASE WHEN EXISTS (SELECT 1
    FROM #emp em2
    WHERE em2.EmpID = em.EmpID AND
    em2.StartDate < em.StartDate AND
    em2.EndDate >= em.StartDate
    ) THEN 0 ELSE 1 END) AS [IsStart]
    FROM #emp em )

    SELECT EmpID
    ,MIN(StartDate) AS [StartDate]
    ,MAX(EndDate) AS [EndDate]
    FROM (SELECT s.*, SUM(isstart) OVER (PARTITION BY EmpID ORDER BY StartDate) AS [grp]
    FROM starts s
    ) s
    GROUP BY EmpID, grp
    ORDER BY EmpID





    share|improve this answer

























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55347342%2fhow-to-calculate-employment-experience-with-special-case%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      Use Distinct to remove dplicated records. Then you can use this query:



      Select totaldays / 365 from 
      (Select Sum(
      DATEDIFF(day, srartdate, enddate )
      ) As totaldays
      )





      share|improve this answer

























      • thanks for the help but, this's not what I'm looking for. as I mentioned there's a function that has some special logic which takes the startdate and enddate as parameters. I just need help figuiring out the correct way to select the startdate, enddate. my expected outpout would be: 1st row: startdate 8/27/2007, enddate 5/9/2008 2nd row: startdate 1/1/2012, enddate 3/25/2019

        – Faris Ahmed
        Mar 25 at 23:23












      • You can nothave unique startdate and enddate. You should calc them record by record which is not important they making via function or using in a function , ... . Otherwise complete your question with ur logics and function and expected resuls

        – Siamak Ferdos
        Mar 25 at 23:30















      0














      Use Distinct to remove dplicated records. Then you can use this query:



      Select totaldays / 365 from 
      (Select Sum(
      DATEDIFF(day, srartdate, enddate )
      ) As totaldays
      )





      share|improve this answer

























      • thanks for the help but, this's not what I'm looking for. as I mentioned there's a function that has some special logic which takes the startdate and enddate as parameters. I just need help figuiring out the correct way to select the startdate, enddate. my expected outpout would be: 1st row: startdate 8/27/2007, enddate 5/9/2008 2nd row: startdate 1/1/2012, enddate 3/25/2019

        – Faris Ahmed
        Mar 25 at 23:23












      • You can nothave unique startdate and enddate. You should calc them record by record which is not important they making via function or using in a function , ... . Otherwise complete your question with ur logics and function and expected resuls

        – Siamak Ferdos
        Mar 25 at 23:30













      0












      0








      0







      Use Distinct to remove dplicated records. Then you can use this query:



      Select totaldays / 365 from 
      (Select Sum(
      DATEDIFF(day, srartdate, enddate )
      ) As totaldays
      )





      share|improve this answer















      Use Distinct to remove dplicated records. Then you can use this query:



      Select totaldays / 365 from 
      (Select Sum(
      DATEDIFF(day, srartdate, enddate )
      ) As totaldays
      )






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Mar 25 at 23:22

























      answered Mar 25 at 23:13









      Siamak FerdosSiamak Ferdos

      1,7981 gold badge19 silver badges45 bronze badges




      1,7981 gold badge19 silver badges45 bronze badges












      • thanks for the help but, this's not what I'm looking for. as I mentioned there's a function that has some special logic which takes the startdate and enddate as parameters. I just need help figuiring out the correct way to select the startdate, enddate. my expected outpout would be: 1st row: startdate 8/27/2007, enddate 5/9/2008 2nd row: startdate 1/1/2012, enddate 3/25/2019

        – Faris Ahmed
        Mar 25 at 23:23












      • You can nothave unique startdate and enddate. You should calc them record by record which is not important they making via function or using in a function , ... . Otherwise complete your question with ur logics and function and expected resuls

        – Siamak Ferdos
        Mar 25 at 23:30

















      • thanks for the help but, this's not what I'm looking for. as I mentioned there's a function that has some special logic which takes the startdate and enddate as parameters. I just need help figuiring out the correct way to select the startdate, enddate. my expected outpout would be: 1st row: startdate 8/27/2007, enddate 5/9/2008 2nd row: startdate 1/1/2012, enddate 3/25/2019

        – Faris Ahmed
        Mar 25 at 23:23












      • You can nothave unique startdate and enddate. You should calc them record by record which is not important they making via function or using in a function , ... . Otherwise complete your question with ur logics and function and expected resuls

        – Siamak Ferdos
        Mar 25 at 23:30
















      thanks for the help but, this's not what I'm looking for. as I mentioned there's a function that has some special logic which takes the startdate and enddate as parameters. I just need help figuiring out the correct way to select the startdate, enddate. my expected outpout would be: 1st row: startdate 8/27/2007, enddate 5/9/2008 2nd row: startdate 1/1/2012, enddate 3/25/2019

      – Faris Ahmed
      Mar 25 at 23:23






      thanks for the help but, this's not what I'm looking for. as I mentioned there's a function that has some special logic which takes the startdate and enddate as parameters. I just need help figuiring out the correct way to select the startdate, enddate. my expected outpout would be: 1st row: startdate 8/27/2007, enddate 5/9/2008 2nd row: startdate 1/1/2012, enddate 3/25/2019

      – Faris Ahmed
      Mar 25 at 23:23














      You can nothave unique startdate and enddate. You should calc them record by record which is not important they making via function or using in a function , ... . Otherwise complete your question with ur logics and function and expected resuls

      – Siamak Ferdos
      Mar 25 at 23:30





      You can nothave unique startdate and enddate. You should calc them record by record which is not important they making via function or using in a function , ... . Otherwise complete your question with ur logics and function and expected resuls

      – Siamak Ferdos
      Mar 25 at 23:30













      0














      This query returns the dates without overlapping:



      select 
      v.startdate startdate,
      min(vv.enddate) enddate
      from view_appemployment v
      inner join view_appemployment vv
      on v.startdate <= vv.enddate
      and not exists (
      select * from view_appemployment vvv
      where vv.enddate >= vvv.startdate and vv.enddate < vvv.enddate
      )
      where not exists (
      select * from view_appemployment vvvv
      where v.startdate > vvvv.startdate and v.startdate <= vvvv.enddate
      )
      group by v.startdate


      See the demo

      Results:



      startdate | enddate 
      ------------------ | ------------------
      27/08/2007 00:00:00 | 09/05/2008 00:00:00
      01/01/2012 00:00:00 | 25/03/2019 00:00:00





      share|improve this answer























      • it will take me sometime to process the logic you wrote but, not sure why I'm not getting any data back when I specify the id for that user. so if I add AND UserID = 100 I don't get any data back.

        – Faris Ahmed
        Mar 25 at 23:54











      • This code assumes operates on view_appemployment. So if you want a where id = ? it must be plugged in every occurrence of view_appemployment, like: select * from view_appemployment where id = ?

        – forpas
        Mar 25 at 23:59











      • Got it. In which part should I add the ISNULL check to replace the enddate with getdate(). actually the way I have the data set up is the fourth employment has no enddate. in this case it should be replaced with today's date

        – Faris Ahmed
        Mar 26 at 0:04











      • Everywhere you see enddate you must do: coalesce(enddate, CONVERT (date, GETDATE()))

        – forpas
        Mar 26 at 0:09











      • Got it. how would i incroporate this part which was part of the original query I used in the past: Age18 is selecting the user date of birth from another table. and ( (StartDate >= Age18) OR (StartDate < Age18 --Individual started position before becoming 18 AND (EndDate > Age18 OR EndDate IS NULL) --position ended after he trurned 18 or still working at same position AND DATEDIFF(YYYY,App.BirthDate, GETDATE()) > 18) -- Individual is now 18 years old )

        – Faris Ahmed
        Mar 26 at 0:23
















      0














      This query returns the dates without overlapping:



      select 
      v.startdate startdate,
      min(vv.enddate) enddate
      from view_appemployment v
      inner join view_appemployment vv
      on v.startdate <= vv.enddate
      and not exists (
      select * from view_appemployment vvv
      where vv.enddate >= vvv.startdate and vv.enddate < vvv.enddate
      )
      where not exists (
      select * from view_appemployment vvvv
      where v.startdate > vvvv.startdate and v.startdate <= vvvv.enddate
      )
      group by v.startdate


      See the demo

      Results:



      startdate | enddate 
      ------------------ | ------------------
      27/08/2007 00:00:00 | 09/05/2008 00:00:00
      01/01/2012 00:00:00 | 25/03/2019 00:00:00





      share|improve this answer























      • it will take me sometime to process the logic you wrote but, not sure why I'm not getting any data back when I specify the id for that user. so if I add AND UserID = 100 I don't get any data back.

        – Faris Ahmed
        Mar 25 at 23:54











      • This code assumes operates on view_appemployment. So if you want a where id = ? it must be plugged in every occurrence of view_appemployment, like: select * from view_appemployment where id = ?

        – forpas
        Mar 25 at 23:59











      • Got it. In which part should I add the ISNULL check to replace the enddate with getdate(). actually the way I have the data set up is the fourth employment has no enddate. in this case it should be replaced with today's date

        – Faris Ahmed
        Mar 26 at 0:04











      • Everywhere you see enddate you must do: coalesce(enddate, CONVERT (date, GETDATE()))

        – forpas
        Mar 26 at 0:09











      • Got it. how would i incroporate this part which was part of the original query I used in the past: Age18 is selecting the user date of birth from another table. and ( (StartDate >= Age18) OR (StartDate < Age18 --Individual started position before becoming 18 AND (EndDate > Age18 OR EndDate IS NULL) --position ended after he trurned 18 or still working at same position AND DATEDIFF(YYYY,App.BirthDate, GETDATE()) > 18) -- Individual is now 18 years old )

        – Faris Ahmed
        Mar 26 at 0:23














      0












      0








      0







      This query returns the dates without overlapping:



      select 
      v.startdate startdate,
      min(vv.enddate) enddate
      from view_appemployment v
      inner join view_appemployment vv
      on v.startdate <= vv.enddate
      and not exists (
      select * from view_appemployment vvv
      where vv.enddate >= vvv.startdate and vv.enddate < vvv.enddate
      )
      where not exists (
      select * from view_appemployment vvvv
      where v.startdate > vvvv.startdate and v.startdate <= vvvv.enddate
      )
      group by v.startdate


      See the demo

      Results:



      startdate | enddate 
      ------------------ | ------------------
      27/08/2007 00:00:00 | 09/05/2008 00:00:00
      01/01/2012 00:00:00 | 25/03/2019 00:00:00





      share|improve this answer













      This query returns the dates without overlapping:



      select 
      v.startdate startdate,
      min(vv.enddate) enddate
      from view_appemployment v
      inner join view_appemployment vv
      on v.startdate <= vv.enddate
      and not exists (
      select * from view_appemployment vvv
      where vv.enddate >= vvv.startdate and vv.enddate < vvv.enddate
      )
      where not exists (
      select * from view_appemployment vvvv
      where v.startdate > vvvv.startdate and v.startdate <= vvvv.enddate
      )
      group by v.startdate


      See the demo

      Results:



      startdate | enddate 
      ------------------ | ------------------
      27/08/2007 00:00:00 | 09/05/2008 00:00:00
      01/01/2012 00:00:00 | 25/03/2019 00:00:00






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Mar 25 at 23:35









      forpasforpas

      32.2k5 gold badges11 silver badges30 bronze badges




      32.2k5 gold badges11 silver badges30 bronze badges












      • it will take me sometime to process the logic you wrote but, not sure why I'm not getting any data back when I specify the id for that user. so if I add AND UserID = 100 I don't get any data back.

        – Faris Ahmed
        Mar 25 at 23:54











      • This code assumes operates on view_appemployment. So if you want a where id = ? it must be plugged in every occurrence of view_appemployment, like: select * from view_appemployment where id = ?

        – forpas
        Mar 25 at 23:59











      • Got it. In which part should I add the ISNULL check to replace the enddate with getdate(). actually the way I have the data set up is the fourth employment has no enddate. in this case it should be replaced with today's date

        – Faris Ahmed
        Mar 26 at 0:04











      • Everywhere you see enddate you must do: coalesce(enddate, CONVERT (date, GETDATE()))

        – forpas
        Mar 26 at 0:09











      • Got it. how would i incroporate this part which was part of the original query I used in the past: Age18 is selecting the user date of birth from another table. and ( (StartDate >= Age18) OR (StartDate < Age18 --Individual started position before becoming 18 AND (EndDate > Age18 OR EndDate IS NULL) --position ended after he trurned 18 or still working at same position AND DATEDIFF(YYYY,App.BirthDate, GETDATE()) > 18) -- Individual is now 18 years old )

        – Faris Ahmed
        Mar 26 at 0:23


















      • it will take me sometime to process the logic you wrote but, not sure why I'm not getting any data back when I specify the id for that user. so if I add AND UserID = 100 I don't get any data back.

        – Faris Ahmed
        Mar 25 at 23:54











      • This code assumes operates on view_appemployment. So if you want a where id = ? it must be plugged in every occurrence of view_appemployment, like: select * from view_appemployment where id = ?

        – forpas
        Mar 25 at 23:59











      • Got it. In which part should I add the ISNULL check to replace the enddate with getdate(). actually the way I have the data set up is the fourth employment has no enddate. in this case it should be replaced with today's date

        – Faris Ahmed
        Mar 26 at 0:04











      • Everywhere you see enddate you must do: coalesce(enddate, CONVERT (date, GETDATE()))

        – forpas
        Mar 26 at 0:09











      • Got it. how would i incroporate this part which was part of the original query I used in the past: Age18 is selecting the user date of birth from another table. and ( (StartDate >= Age18) OR (StartDate < Age18 --Individual started position before becoming 18 AND (EndDate > Age18 OR EndDate IS NULL) --position ended after he trurned 18 or still working at same position AND DATEDIFF(YYYY,App.BirthDate, GETDATE()) > 18) -- Individual is now 18 years old )

        – Faris Ahmed
        Mar 26 at 0:23

















      it will take me sometime to process the logic you wrote but, not sure why I'm not getting any data back when I specify the id for that user. so if I add AND UserID = 100 I don't get any data back.

      – Faris Ahmed
      Mar 25 at 23:54





      it will take me sometime to process the logic you wrote but, not sure why I'm not getting any data back when I specify the id for that user. so if I add AND UserID = 100 I don't get any data back.

      – Faris Ahmed
      Mar 25 at 23:54













      This code assumes operates on view_appemployment. So if you want a where id = ? it must be plugged in every occurrence of view_appemployment, like: select * from view_appemployment where id = ?

      – forpas
      Mar 25 at 23:59





      This code assumes operates on view_appemployment. So if you want a where id = ? it must be plugged in every occurrence of view_appemployment, like: select * from view_appemployment where id = ?

      – forpas
      Mar 25 at 23:59













      Got it. In which part should I add the ISNULL check to replace the enddate with getdate(). actually the way I have the data set up is the fourth employment has no enddate. in this case it should be replaced with today's date

      – Faris Ahmed
      Mar 26 at 0:04





      Got it. In which part should I add the ISNULL check to replace the enddate with getdate(). actually the way I have the data set up is the fourth employment has no enddate. in this case it should be replaced with today's date

      – Faris Ahmed
      Mar 26 at 0:04













      Everywhere you see enddate you must do: coalesce(enddate, CONVERT (date, GETDATE()))

      – forpas
      Mar 26 at 0:09





      Everywhere you see enddate you must do: coalesce(enddate, CONVERT (date, GETDATE()))

      – forpas
      Mar 26 at 0:09













      Got it. how would i incroporate this part which was part of the original query I used in the past: Age18 is selecting the user date of birth from another table. and ( (StartDate >= Age18) OR (StartDate < Age18 --Individual started position before becoming 18 AND (EndDate > Age18 OR EndDate IS NULL) --position ended after he trurned 18 or still working at same position AND DATEDIFF(YYYY,App.BirthDate, GETDATE()) > 18) -- Individual is now 18 years old )

      – Faris Ahmed
      Mar 26 at 0:23






      Got it. how would i incroporate this part which was part of the original query I used in the past: Age18 is selecting the user date of birth from another table. and ( (StartDate >= Age18) OR (StartDate < Age18 --Individual started position before becoming 18 AND (EndDate > Age18 OR EndDate IS NULL) --position ended after he trurned 18 or still working at same position AND DATEDIFF(YYYY,App.BirthDate, GETDATE()) > 18) -- Individual is now 18 years old )

      – Faris Ahmed
      Mar 26 at 0:23












      0














      Please try this:



      RESULT PIC



      SELECT concat(id," row: start date ",date_format(start_date,'%d/%m/%y')," end date ",date_format(end_date,'%d/%m/%y'))as dateinfo FROM `dates`





      share|improve this answer










      New contributor



      shaik sazeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.























        0














        Please try this:



        RESULT PIC



        SELECT concat(id," row: start date ",date_format(start_date,'%d/%m/%y')," end date ",date_format(end_date,'%d/%m/%y'))as dateinfo FROM `dates`





        share|improve this answer










        New contributor



        shaik sazeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





















          0












          0








          0







          Please try this:



          RESULT PIC



          SELECT concat(id," row: start date ",date_format(start_date,'%d/%m/%y')," end date ",date_format(end_date,'%d/%m/%y'))as dateinfo FROM `dates`





          share|improve this answer










          New contributor



          shaik sazeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.









          Please try this:



          RESULT PIC



          SELECT concat(id," row: start date ",date_format(start_date,'%d/%m/%y')," end date ",date_format(end_date,'%d/%m/%y'))as dateinfo FROM `dates`






          share|improve this answer










          New contributor



          shaik sazeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.








          share|improve this answer



          share|improve this answer








          edited Jul 3 at 4:27









          PowerStat

          2,0573 gold badges15 silver badges28 bronze badges




          2,0573 gold badges15 silver badges28 bronze badges






          New contributor



          shaik sazeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.








          answered Jul 3 at 3:53









          shaik sazeershaik sazeer

          12 bronze badges




          12 bronze badges




          New contributor



          shaik sazeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.




          New contributor




          shaik sazeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.























              0














              This is a Gaps & Islands in Sequences problem, the following query should do what you want:



              CREATE TABLE #emp (empid int, startdate date,enddate date)
              INSERT INTO #emp VALUES
              (1,'2007-08-27','2008-05-09'),
              (1,'2007-08-27','2008-05-09'),
              (1,'2012-01-01','2018-07-31'),
              (1,'2013-01-06','2019-03-25')

              ;WITH starts AS (
              SELECT em.*,
              (CASE WHEN EXISTS (SELECT 1
              FROM #emp em2
              WHERE em2.EmpID = em.EmpID AND
              em2.StartDate < em.StartDate AND
              em2.EndDate >= em.StartDate
              ) THEN 0 ELSE 1 END) AS [IsStart]
              FROM #emp em )

              SELECT EmpID
              ,MIN(StartDate) AS [StartDate]
              ,MAX(EndDate) AS [EndDate]
              FROM (SELECT s.*, SUM(isstart) OVER (PARTITION BY EmpID ORDER BY StartDate) AS [grp]
              FROM starts s
              ) s
              GROUP BY EmpID, grp
              ORDER BY EmpID





              share|improve this answer



























                0














                This is a Gaps & Islands in Sequences problem, the following query should do what you want:



                CREATE TABLE #emp (empid int, startdate date,enddate date)
                INSERT INTO #emp VALUES
                (1,'2007-08-27','2008-05-09'),
                (1,'2007-08-27','2008-05-09'),
                (1,'2012-01-01','2018-07-31'),
                (1,'2013-01-06','2019-03-25')

                ;WITH starts AS (
                SELECT em.*,
                (CASE WHEN EXISTS (SELECT 1
                FROM #emp em2
                WHERE em2.EmpID = em.EmpID AND
                em2.StartDate < em.StartDate AND
                em2.EndDate >= em.StartDate
                ) THEN 0 ELSE 1 END) AS [IsStart]
                FROM #emp em )

                SELECT EmpID
                ,MIN(StartDate) AS [StartDate]
                ,MAX(EndDate) AS [EndDate]
                FROM (SELECT s.*, SUM(isstart) OVER (PARTITION BY EmpID ORDER BY StartDate) AS [grp]
                FROM starts s
                ) s
                GROUP BY EmpID, grp
                ORDER BY EmpID





                share|improve this answer

























                  0












                  0








                  0







                  This is a Gaps & Islands in Sequences problem, the following query should do what you want:



                  CREATE TABLE #emp (empid int, startdate date,enddate date)
                  INSERT INTO #emp VALUES
                  (1,'2007-08-27','2008-05-09'),
                  (1,'2007-08-27','2008-05-09'),
                  (1,'2012-01-01','2018-07-31'),
                  (1,'2013-01-06','2019-03-25')

                  ;WITH starts AS (
                  SELECT em.*,
                  (CASE WHEN EXISTS (SELECT 1
                  FROM #emp em2
                  WHERE em2.EmpID = em.EmpID AND
                  em2.StartDate < em.StartDate AND
                  em2.EndDate >= em.StartDate
                  ) THEN 0 ELSE 1 END) AS [IsStart]
                  FROM #emp em )

                  SELECT EmpID
                  ,MIN(StartDate) AS [StartDate]
                  ,MAX(EndDate) AS [EndDate]
                  FROM (SELECT s.*, SUM(isstart) OVER (PARTITION BY EmpID ORDER BY StartDate) AS [grp]
                  FROM starts s
                  ) s
                  GROUP BY EmpID, grp
                  ORDER BY EmpID





                  share|improve this answer













                  This is a Gaps & Islands in Sequences problem, the following query should do what you want:



                  CREATE TABLE #emp (empid int, startdate date,enddate date)
                  INSERT INTO #emp VALUES
                  (1,'2007-08-27','2008-05-09'),
                  (1,'2007-08-27','2008-05-09'),
                  (1,'2012-01-01','2018-07-31'),
                  (1,'2013-01-06','2019-03-25')

                  ;WITH starts AS (
                  SELECT em.*,
                  (CASE WHEN EXISTS (SELECT 1
                  FROM #emp em2
                  WHERE em2.EmpID = em.EmpID AND
                  em2.StartDate < em.StartDate AND
                  em2.EndDate >= em.StartDate
                  ) THEN 0 ELSE 1 END) AS [IsStart]
                  FROM #emp em )

                  SELECT EmpID
                  ,MIN(StartDate) AS [StartDate]
                  ,MAX(EndDate) AS [EndDate]
                  FROM (SELECT s.*, SUM(isstart) OVER (PARTITION BY EmpID ORDER BY StartDate) AS [grp]
                  FROM starts s
                  ) s
                  GROUP BY EmpID, grp
                  ORDER BY EmpID






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jul 3 at 12:29









                  MJoyMJoy

                  6861 gold badge3 silver badges14 bronze badges




                  6861 gold badge3 silver badges14 bronze badges



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55347342%2fhow-to-calculate-employment-experience-with-special-case%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현