Set column value based on another column's value












0















I have a table that contains 4 columns:



ItemId, ItemPrice, DateFrom, DateTo


The table contains information about items, their prices and the day that the prices changed



for example:



Before update



What I want to do, is to fill the DateTo column so I know what for how long the price has lasted and if it still lasts



The results I expect:



After update



An important note is also that the count of the price changes is unknown, for some items it changes 3 times and for some it doesn't change at all and the price remains unchanged until this day.



Any kind of help will be greatly appreciated.










share|improve this question





























    0















    I have a table that contains 4 columns:



    ItemId, ItemPrice, DateFrom, DateTo


    The table contains information about items, their prices and the day that the prices changed



    for example:



    Before update



    What I want to do, is to fill the DateTo column so I know what for how long the price has lasted and if it still lasts



    The results I expect:



    After update



    An important note is also that the count of the price changes is unknown, for some items it changes 3 times and for some it doesn't change at all and the price remains unchanged until this day.



    Any kind of help will be greatly appreciated.










    share|improve this question



























      0












      0








      0


      1






      I have a table that contains 4 columns:



      ItemId, ItemPrice, DateFrom, DateTo


      The table contains information about items, their prices and the day that the prices changed



      for example:



      Before update



      What I want to do, is to fill the DateTo column so I know what for how long the price has lasted and if it still lasts



      The results I expect:



      After update



      An important note is also that the count of the price changes is unknown, for some items it changes 3 times and for some it doesn't change at all and the price remains unchanged until this day.



      Any kind of help will be greatly appreciated.










      share|improve this question
















      I have a table that contains 4 columns:



      ItemId, ItemPrice, DateFrom, DateTo


      The table contains information about items, their prices and the day that the prices changed



      for example:



      Before update



      What I want to do, is to fill the DateTo column so I know what for how long the price has lasted and if it still lasts



      The results I expect:



      After update



      An important note is also that the count of the price changes is unknown, for some items it changes 3 times and for some it doesn't change at all and the price remains unchanged until this day.



      Any kind of help will be greatly appreciated.







      sql sql-server tsql






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 12:26







      mjohansen

















      asked Nov 22 '18 at 12:25









      mjohansenmjohansen

      213




      213
























          5 Answers
          5






          active

          oldest

          votes


















          0














          A view would be far better solution to this, as there's no need to have a AFTER UPDATE trigger, and you can't persist a column with the value GETDATE() (thus you would have to update the value of DateTo at the start of every day). This will get you the result you are after:



          CREATE VIEW YourView AS

          SELECT ItemId,
          ItemPrice,
          DateFrom,
          LEAD(DATEADD(DAY,-1,DateFrom),1,GETDATE()) OVER (PARTITION BY ItemId ORDER BY DateFrom ASC) AS DateTo
          FROM YourTable;





          share|improve this answer
























          • This works exactly as I needed it to work, thank you so much!

            – mjohansen
            Nov 22 '18 at 12:57











          • You're welcome @mjohansen . Please remember to mark the answer as a solution if so, so that others with the same/similar question know it helped you. Thanks.

            – Larnu
            Nov 22 '18 at 13:00





















          0














          Try below query - Check it online



          DECLARE @Tab TABLE
          (
          itemid INT,
          itemprice INT,
          DateFrom Date
          )

          INSERT INTO @Tab VALUES (111,5000,'2018-01-01'),(111,8000,'2018-02-24'),(111,6000,'2018-03-12')

          SELECT *,ISNULL(
          (SELECT top 1 DATEADD(day,-1,DateFrom)
          from @tab t1
          WHERE t1.itemid= t2.itemid
          AND t1.Datefrom > t2.Datefrom) , GETDATE()) AS DateTo
          FROM @tab t2





          share|improve this answer
























          • Doing SELECT top 1 without ORDER BY makes no sense: it will give unpredictable (quasi-random) results.

            – Peter B
            Nov 22 '18 at 13:03



















          0














          You need to set the DateTo of each record to "the smallest of all From-dates (for the same ItemId) that are bigger than its own DateFrom, minus 1 day".



          And for those where it couldn't be found, set it to GetDate().



          In SQL:



          UPDATE PriceTable
          SET DateTo = (SELECT DATEADD(d, -1, MIN(DateFrom))
          FROM PriceTable P2
          WHERE P2.ItemId = P1.ItemId
          AND P2.DateFrom > P1.DateFrom)
          FROM PriceTable P1

          UPDATE PriceTable
          SET DateTo = GETDATE()
          WHERE DateTo IS NULL


          Or combined into one step:



          UPDATE PriceTable
          SET DateTo = (SELECT ISNULL(DATEADD(d, -1, MIN(DateFrom)), GETDATE())
          FROM PriceTable P2
          WHERE P2.ItemId = P1.ItemId
          AND P2.DateFrom > P1.DateFrom)
          FROM PriceTable P1





          share|improve this answer































            0














            You can create date_to column on adhoc basic as you see. below



            SELECT ItemId, ItemPrice, DateFrom,
            DATEADD(day, 1, lead(DateFrom,1,getdate()))
            over (order by ItemId asc ,DateFrom asc) as date_to
            FROM tbl


            You can update value as



            UPDATE tbl T2 SET dateto= 
            (SELECT
            DATEADD(day, 1, lead(DateFrom,1,getdate())) over (order by ItemId asc ,DateFrom asc)
            FROM tbl T1 where T1.ItemId=T1.ItemId AND T1.ItemId = T2.ItemId AND T1.DateFrom =
            T2.DateFrom)





            share|improve this answer































              -1














              For future add trigger who update dateTo on insert new row, now you must select previous value DateFrom



              SELECT ItemId, ItemPrice, DateFrom,
              SELECT(DateFrom FROM tbl WHERE ItemId IN (
              SELECT TOP 1 ItemId FROM tbl WHERE tbl.ItemId = tbl1.ItemId
              WHERE tbl.DateFrom < tbl1.DateFrom
              ORDER BY tbl.DateFrom DESC)
              ) FROM tbl AS tbl1





              share|improve this answer


























              • This doesn't give the OP an answer; it gives them an idea. Also, how does this solve the problem when there is no next value? If the default value of DateTo is set to GETDATE() it'll be stale after (at most) 24 hours.

                – Larnu
                Nov 22 '18 at 12:35













              • @Larnu updated answer, And it should add something like IFNULL(_QUERY_, GETDATE())

                – bato3
                Nov 22 '18 at 12:44











              • That query won't run I'm afraid; for example a subquery in the SELECT needs to be wrapped in paranthesis(()). It also doesn't cater the latest value and (a valid) query would result in 3 scans of the table; which seems a little over kill.

                – Larnu
                Nov 22 '18 at 12:44













              • My mistake is that I give a solution hint for MySQL. And you can reduce the number of scans to 2, but then you are not sure about the correctness of the returned data

                – bato3
                Nov 22 '18 at 12:49











              • This is a SQL Server question, not MySQL.

                – Larnu
                Nov 22 '18 at 12:50











              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%2f53430982%2fset-column-value-based-on-another-columns-value%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              5 Answers
              5






              active

              oldest

              votes








              5 Answers
              5






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              A view would be far better solution to this, as there's no need to have a AFTER UPDATE trigger, and you can't persist a column with the value GETDATE() (thus you would have to update the value of DateTo at the start of every day). This will get you the result you are after:



              CREATE VIEW YourView AS

              SELECT ItemId,
              ItemPrice,
              DateFrom,
              LEAD(DATEADD(DAY,-1,DateFrom),1,GETDATE()) OVER (PARTITION BY ItemId ORDER BY DateFrom ASC) AS DateTo
              FROM YourTable;





              share|improve this answer
























              • This works exactly as I needed it to work, thank you so much!

                – mjohansen
                Nov 22 '18 at 12:57











              • You're welcome @mjohansen . Please remember to mark the answer as a solution if so, so that others with the same/similar question know it helped you. Thanks.

                – Larnu
                Nov 22 '18 at 13:00


















              0














              A view would be far better solution to this, as there's no need to have a AFTER UPDATE trigger, and you can't persist a column with the value GETDATE() (thus you would have to update the value of DateTo at the start of every day). This will get you the result you are after:



              CREATE VIEW YourView AS

              SELECT ItemId,
              ItemPrice,
              DateFrom,
              LEAD(DATEADD(DAY,-1,DateFrom),1,GETDATE()) OVER (PARTITION BY ItemId ORDER BY DateFrom ASC) AS DateTo
              FROM YourTable;





              share|improve this answer
























              • This works exactly as I needed it to work, thank you so much!

                – mjohansen
                Nov 22 '18 at 12:57











              • You're welcome @mjohansen . Please remember to mark the answer as a solution if so, so that others with the same/similar question know it helped you. Thanks.

                – Larnu
                Nov 22 '18 at 13:00
















              0












              0








              0







              A view would be far better solution to this, as there's no need to have a AFTER UPDATE trigger, and you can't persist a column with the value GETDATE() (thus you would have to update the value of DateTo at the start of every day). This will get you the result you are after:



              CREATE VIEW YourView AS

              SELECT ItemId,
              ItemPrice,
              DateFrom,
              LEAD(DATEADD(DAY,-1,DateFrom),1,GETDATE()) OVER (PARTITION BY ItemId ORDER BY DateFrom ASC) AS DateTo
              FROM YourTable;





              share|improve this answer













              A view would be far better solution to this, as there's no need to have a AFTER UPDATE trigger, and you can't persist a column with the value GETDATE() (thus you would have to update the value of DateTo at the start of every day). This will get you the result you are after:



              CREATE VIEW YourView AS

              SELECT ItemId,
              ItemPrice,
              DateFrom,
              LEAD(DATEADD(DAY,-1,DateFrom),1,GETDATE()) OVER (PARTITION BY ItemId ORDER BY DateFrom ASC) AS DateTo
              FROM YourTable;






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 22 '18 at 12:30









              LarnuLarnu

              17.1k41630




              17.1k41630













              • This works exactly as I needed it to work, thank you so much!

                – mjohansen
                Nov 22 '18 at 12:57











              • You're welcome @mjohansen . Please remember to mark the answer as a solution if so, so that others with the same/similar question know it helped you. Thanks.

                – Larnu
                Nov 22 '18 at 13:00





















              • This works exactly as I needed it to work, thank you so much!

                – mjohansen
                Nov 22 '18 at 12:57











              • You're welcome @mjohansen . Please remember to mark the answer as a solution if so, so that others with the same/similar question know it helped you. Thanks.

                – Larnu
                Nov 22 '18 at 13:00



















              This works exactly as I needed it to work, thank you so much!

              – mjohansen
              Nov 22 '18 at 12:57





              This works exactly as I needed it to work, thank you so much!

              – mjohansen
              Nov 22 '18 at 12:57













              You're welcome @mjohansen . Please remember to mark the answer as a solution if so, so that others with the same/similar question know it helped you. Thanks.

              – Larnu
              Nov 22 '18 at 13:00







              You're welcome @mjohansen . Please remember to mark the answer as a solution if so, so that others with the same/similar question know it helped you. Thanks.

              – Larnu
              Nov 22 '18 at 13:00















              0














              Try below query - Check it online



              DECLARE @Tab TABLE
              (
              itemid INT,
              itemprice INT,
              DateFrom Date
              )

              INSERT INTO @Tab VALUES (111,5000,'2018-01-01'),(111,8000,'2018-02-24'),(111,6000,'2018-03-12')

              SELECT *,ISNULL(
              (SELECT top 1 DATEADD(day,-1,DateFrom)
              from @tab t1
              WHERE t1.itemid= t2.itemid
              AND t1.Datefrom > t2.Datefrom) , GETDATE()) AS DateTo
              FROM @tab t2





              share|improve this answer
























              • Doing SELECT top 1 without ORDER BY makes no sense: it will give unpredictable (quasi-random) results.

                – Peter B
                Nov 22 '18 at 13:03
















              0














              Try below query - Check it online



              DECLARE @Tab TABLE
              (
              itemid INT,
              itemprice INT,
              DateFrom Date
              )

              INSERT INTO @Tab VALUES (111,5000,'2018-01-01'),(111,8000,'2018-02-24'),(111,6000,'2018-03-12')

              SELECT *,ISNULL(
              (SELECT top 1 DATEADD(day,-1,DateFrom)
              from @tab t1
              WHERE t1.itemid= t2.itemid
              AND t1.Datefrom > t2.Datefrom) , GETDATE()) AS DateTo
              FROM @tab t2





              share|improve this answer
























              • Doing SELECT top 1 without ORDER BY makes no sense: it will give unpredictable (quasi-random) results.

                – Peter B
                Nov 22 '18 at 13:03














              0












              0








              0







              Try below query - Check it online



              DECLARE @Tab TABLE
              (
              itemid INT,
              itemprice INT,
              DateFrom Date
              )

              INSERT INTO @Tab VALUES (111,5000,'2018-01-01'),(111,8000,'2018-02-24'),(111,6000,'2018-03-12')

              SELECT *,ISNULL(
              (SELECT top 1 DATEADD(day,-1,DateFrom)
              from @tab t1
              WHERE t1.itemid= t2.itemid
              AND t1.Datefrom > t2.Datefrom) , GETDATE()) AS DateTo
              FROM @tab t2





              share|improve this answer













              Try below query - Check it online



              DECLARE @Tab TABLE
              (
              itemid INT,
              itemprice INT,
              DateFrom Date
              )

              INSERT INTO @Tab VALUES (111,5000,'2018-01-01'),(111,8000,'2018-02-24'),(111,6000,'2018-03-12')

              SELECT *,ISNULL(
              (SELECT top 1 DATEADD(day,-1,DateFrom)
              from @tab t1
              WHERE t1.itemid= t2.itemid
              AND t1.Datefrom > t2.Datefrom) , GETDATE()) AS DateTo
              FROM @tab t2






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 22 '18 at 12:49









              ZerotoinfinityZerotoinfinity

              2,2032098175




              2,2032098175













              • Doing SELECT top 1 without ORDER BY makes no sense: it will give unpredictable (quasi-random) results.

                – Peter B
                Nov 22 '18 at 13:03



















              • Doing SELECT top 1 without ORDER BY makes no sense: it will give unpredictable (quasi-random) results.

                – Peter B
                Nov 22 '18 at 13:03

















              Doing SELECT top 1 without ORDER BY makes no sense: it will give unpredictable (quasi-random) results.

              – Peter B
              Nov 22 '18 at 13:03





              Doing SELECT top 1 without ORDER BY makes no sense: it will give unpredictable (quasi-random) results.

              – Peter B
              Nov 22 '18 at 13:03











              0














              You need to set the DateTo of each record to "the smallest of all From-dates (for the same ItemId) that are bigger than its own DateFrom, minus 1 day".



              And for those where it couldn't be found, set it to GetDate().



              In SQL:



              UPDATE PriceTable
              SET DateTo = (SELECT DATEADD(d, -1, MIN(DateFrom))
              FROM PriceTable P2
              WHERE P2.ItemId = P1.ItemId
              AND P2.DateFrom > P1.DateFrom)
              FROM PriceTable P1

              UPDATE PriceTable
              SET DateTo = GETDATE()
              WHERE DateTo IS NULL


              Or combined into one step:



              UPDATE PriceTable
              SET DateTo = (SELECT ISNULL(DATEADD(d, -1, MIN(DateFrom)), GETDATE())
              FROM PriceTable P2
              WHERE P2.ItemId = P1.ItemId
              AND P2.DateFrom > P1.DateFrom)
              FROM PriceTable P1





              share|improve this answer




























                0














                You need to set the DateTo of each record to "the smallest of all From-dates (for the same ItemId) that are bigger than its own DateFrom, minus 1 day".



                And for those where it couldn't be found, set it to GetDate().



                In SQL:



                UPDATE PriceTable
                SET DateTo = (SELECT DATEADD(d, -1, MIN(DateFrom))
                FROM PriceTable P2
                WHERE P2.ItemId = P1.ItemId
                AND P2.DateFrom > P1.DateFrom)
                FROM PriceTable P1

                UPDATE PriceTable
                SET DateTo = GETDATE()
                WHERE DateTo IS NULL


                Or combined into one step:



                UPDATE PriceTable
                SET DateTo = (SELECT ISNULL(DATEADD(d, -1, MIN(DateFrom)), GETDATE())
                FROM PriceTable P2
                WHERE P2.ItemId = P1.ItemId
                AND P2.DateFrom > P1.DateFrom)
                FROM PriceTable P1





                share|improve this answer


























                  0












                  0








                  0







                  You need to set the DateTo of each record to "the smallest of all From-dates (for the same ItemId) that are bigger than its own DateFrom, minus 1 day".



                  And for those where it couldn't be found, set it to GetDate().



                  In SQL:



                  UPDATE PriceTable
                  SET DateTo = (SELECT DATEADD(d, -1, MIN(DateFrom))
                  FROM PriceTable P2
                  WHERE P2.ItemId = P1.ItemId
                  AND P2.DateFrom > P1.DateFrom)
                  FROM PriceTable P1

                  UPDATE PriceTable
                  SET DateTo = GETDATE()
                  WHERE DateTo IS NULL


                  Or combined into one step:



                  UPDATE PriceTable
                  SET DateTo = (SELECT ISNULL(DATEADD(d, -1, MIN(DateFrom)), GETDATE())
                  FROM PriceTable P2
                  WHERE P2.ItemId = P1.ItemId
                  AND P2.DateFrom > P1.DateFrom)
                  FROM PriceTable P1





                  share|improve this answer













                  You need to set the DateTo of each record to "the smallest of all From-dates (for the same ItemId) that are bigger than its own DateFrom, minus 1 day".



                  And for those where it couldn't be found, set it to GetDate().



                  In SQL:



                  UPDATE PriceTable
                  SET DateTo = (SELECT DATEADD(d, -1, MIN(DateFrom))
                  FROM PriceTable P2
                  WHERE P2.ItemId = P1.ItemId
                  AND P2.DateFrom > P1.DateFrom)
                  FROM PriceTable P1

                  UPDATE PriceTable
                  SET DateTo = GETDATE()
                  WHERE DateTo IS NULL


                  Or combined into one step:



                  UPDATE PriceTable
                  SET DateTo = (SELECT ISNULL(DATEADD(d, -1, MIN(DateFrom)), GETDATE())
                  FROM PriceTable P2
                  WHERE P2.ItemId = P1.ItemId
                  AND P2.DateFrom > P1.DateFrom)
                  FROM PriceTable P1






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 22 '18 at 13:01









                  Peter BPeter B

                  12.9k51941




                  12.9k51941























                      0














                      You can create date_to column on adhoc basic as you see. below



                      SELECT ItemId, ItemPrice, DateFrom,
                      DATEADD(day, 1, lead(DateFrom,1,getdate()))
                      over (order by ItemId asc ,DateFrom asc) as date_to
                      FROM tbl


                      You can update value as



                      UPDATE tbl T2 SET dateto= 
                      (SELECT
                      DATEADD(day, 1, lead(DateFrom,1,getdate())) over (order by ItemId asc ,DateFrom asc)
                      FROM tbl T1 where T1.ItemId=T1.ItemId AND T1.ItemId = T2.ItemId AND T1.DateFrom =
                      T2.DateFrom)





                      share|improve this answer




























                        0














                        You can create date_to column on adhoc basic as you see. below



                        SELECT ItemId, ItemPrice, DateFrom,
                        DATEADD(day, 1, lead(DateFrom,1,getdate()))
                        over (order by ItemId asc ,DateFrom asc) as date_to
                        FROM tbl


                        You can update value as



                        UPDATE tbl T2 SET dateto= 
                        (SELECT
                        DATEADD(day, 1, lead(DateFrom,1,getdate())) over (order by ItemId asc ,DateFrom asc)
                        FROM tbl T1 where T1.ItemId=T1.ItemId AND T1.ItemId = T2.ItemId AND T1.DateFrom =
                        T2.DateFrom)





                        share|improve this answer


























                          0












                          0








                          0







                          You can create date_to column on adhoc basic as you see. below



                          SELECT ItemId, ItemPrice, DateFrom,
                          DATEADD(day, 1, lead(DateFrom,1,getdate()))
                          over (order by ItemId asc ,DateFrom asc) as date_to
                          FROM tbl


                          You can update value as



                          UPDATE tbl T2 SET dateto= 
                          (SELECT
                          DATEADD(day, 1, lead(DateFrom,1,getdate())) over (order by ItemId asc ,DateFrom asc)
                          FROM tbl T1 where T1.ItemId=T1.ItemId AND T1.ItemId = T2.ItemId AND T1.DateFrom =
                          T2.DateFrom)





                          share|improve this answer













                          You can create date_to column on adhoc basic as you see. below



                          SELECT ItemId, ItemPrice, DateFrom,
                          DATEADD(day, 1, lead(DateFrom,1,getdate()))
                          over (order by ItemId asc ,DateFrom asc) as date_to
                          FROM tbl


                          You can update value as



                          UPDATE tbl T2 SET dateto= 
                          (SELECT
                          DATEADD(day, 1, lead(DateFrom,1,getdate())) over (order by ItemId asc ,DateFrom asc)
                          FROM tbl T1 where T1.ItemId=T1.ItemId AND T1.ItemId = T2.ItemId AND T1.DateFrom =
                          T2.DateFrom)






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 22 '18 at 13:10









                          kiran gadhekiran gadhe

                          62617




                          62617























                              -1














                              For future add trigger who update dateTo on insert new row, now you must select previous value DateFrom



                              SELECT ItemId, ItemPrice, DateFrom,
                              SELECT(DateFrom FROM tbl WHERE ItemId IN (
                              SELECT TOP 1 ItemId FROM tbl WHERE tbl.ItemId = tbl1.ItemId
                              WHERE tbl.DateFrom < tbl1.DateFrom
                              ORDER BY tbl.DateFrom DESC)
                              ) FROM tbl AS tbl1





                              share|improve this answer


























                              • This doesn't give the OP an answer; it gives them an idea. Also, how does this solve the problem when there is no next value? If the default value of DateTo is set to GETDATE() it'll be stale after (at most) 24 hours.

                                – Larnu
                                Nov 22 '18 at 12:35













                              • @Larnu updated answer, And it should add something like IFNULL(_QUERY_, GETDATE())

                                – bato3
                                Nov 22 '18 at 12:44











                              • That query won't run I'm afraid; for example a subquery in the SELECT needs to be wrapped in paranthesis(()). It also doesn't cater the latest value and (a valid) query would result in 3 scans of the table; which seems a little over kill.

                                – Larnu
                                Nov 22 '18 at 12:44













                              • My mistake is that I give a solution hint for MySQL. And you can reduce the number of scans to 2, but then you are not sure about the correctness of the returned data

                                – bato3
                                Nov 22 '18 at 12:49











                              • This is a SQL Server question, not MySQL.

                                – Larnu
                                Nov 22 '18 at 12:50
















                              -1














                              For future add trigger who update dateTo on insert new row, now you must select previous value DateFrom



                              SELECT ItemId, ItemPrice, DateFrom,
                              SELECT(DateFrom FROM tbl WHERE ItemId IN (
                              SELECT TOP 1 ItemId FROM tbl WHERE tbl.ItemId = tbl1.ItemId
                              WHERE tbl.DateFrom < tbl1.DateFrom
                              ORDER BY tbl.DateFrom DESC)
                              ) FROM tbl AS tbl1





                              share|improve this answer


























                              • This doesn't give the OP an answer; it gives them an idea. Also, how does this solve the problem when there is no next value? If the default value of DateTo is set to GETDATE() it'll be stale after (at most) 24 hours.

                                – Larnu
                                Nov 22 '18 at 12:35













                              • @Larnu updated answer, And it should add something like IFNULL(_QUERY_, GETDATE())

                                – bato3
                                Nov 22 '18 at 12:44











                              • That query won't run I'm afraid; for example a subquery in the SELECT needs to be wrapped in paranthesis(()). It also doesn't cater the latest value and (a valid) query would result in 3 scans of the table; which seems a little over kill.

                                – Larnu
                                Nov 22 '18 at 12:44













                              • My mistake is that I give a solution hint for MySQL. And you can reduce the number of scans to 2, but then you are not sure about the correctness of the returned data

                                – bato3
                                Nov 22 '18 at 12:49











                              • This is a SQL Server question, not MySQL.

                                – Larnu
                                Nov 22 '18 at 12:50














                              -1












                              -1








                              -1







                              For future add trigger who update dateTo on insert new row, now you must select previous value DateFrom



                              SELECT ItemId, ItemPrice, DateFrom,
                              SELECT(DateFrom FROM tbl WHERE ItemId IN (
                              SELECT TOP 1 ItemId FROM tbl WHERE tbl.ItemId = tbl1.ItemId
                              WHERE tbl.DateFrom < tbl1.DateFrom
                              ORDER BY tbl.DateFrom DESC)
                              ) FROM tbl AS tbl1





                              share|improve this answer















                              For future add trigger who update dateTo on insert new row, now you must select previous value DateFrom



                              SELECT ItemId, ItemPrice, DateFrom,
                              SELECT(DateFrom FROM tbl WHERE ItemId IN (
                              SELECT TOP 1 ItemId FROM tbl WHERE tbl.ItemId = tbl1.ItemId
                              WHERE tbl.DateFrom < tbl1.DateFrom
                              ORDER BY tbl.DateFrom DESC)
                              ) FROM tbl AS tbl1






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Nov 22 '18 at 12:59

























                              answered Nov 22 '18 at 12:30









                              bato3bato3

                              877617




                              877617













                              • This doesn't give the OP an answer; it gives them an idea. Also, how does this solve the problem when there is no next value? If the default value of DateTo is set to GETDATE() it'll be stale after (at most) 24 hours.

                                – Larnu
                                Nov 22 '18 at 12:35













                              • @Larnu updated answer, And it should add something like IFNULL(_QUERY_, GETDATE())

                                – bato3
                                Nov 22 '18 at 12:44











                              • That query won't run I'm afraid; for example a subquery in the SELECT needs to be wrapped in paranthesis(()). It also doesn't cater the latest value and (a valid) query would result in 3 scans of the table; which seems a little over kill.

                                – Larnu
                                Nov 22 '18 at 12:44













                              • My mistake is that I give a solution hint for MySQL. And you can reduce the number of scans to 2, but then you are not sure about the correctness of the returned data

                                – bato3
                                Nov 22 '18 at 12:49











                              • This is a SQL Server question, not MySQL.

                                – Larnu
                                Nov 22 '18 at 12:50



















                              • This doesn't give the OP an answer; it gives them an idea. Also, how does this solve the problem when there is no next value? If the default value of DateTo is set to GETDATE() it'll be stale after (at most) 24 hours.

                                – Larnu
                                Nov 22 '18 at 12:35













                              • @Larnu updated answer, And it should add something like IFNULL(_QUERY_, GETDATE())

                                – bato3
                                Nov 22 '18 at 12:44











                              • That query won't run I'm afraid; for example a subquery in the SELECT needs to be wrapped in paranthesis(()). It also doesn't cater the latest value and (a valid) query would result in 3 scans of the table; which seems a little over kill.

                                – Larnu
                                Nov 22 '18 at 12:44













                              • My mistake is that I give a solution hint for MySQL. And you can reduce the number of scans to 2, but then you are not sure about the correctness of the returned data

                                – bato3
                                Nov 22 '18 at 12:49











                              • This is a SQL Server question, not MySQL.

                                – Larnu
                                Nov 22 '18 at 12:50

















                              This doesn't give the OP an answer; it gives them an idea. Also, how does this solve the problem when there is no next value? If the default value of DateTo is set to GETDATE() it'll be stale after (at most) 24 hours.

                              – Larnu
                              Nov 22 '18 at 12:35







                              This doesn't give the OP an answer; it gives them an idea. Also, how does this solve the problem when there is no next value? If the default value of DateTo is set to GETDATE() it'll be stale after (at most) 24 hours.

                              – Larnu
                              Nov 22 '18 at 12:35















                              @Larnu updated answer, And it should add something like IFNULL(_QUERY_, GETDATE())

                              – bato3
                              Nov 22 '18 at 12:44





                              @Larnu updated answer, And it should add something like IFNULL(_QUERY_, GETDATE())

                              – bato3
                              Nov 22 '18 at 12:44













                              That query won't run I'm afraid; for example a subquery in the SELECT needs to be wrapped in paranthesis(()). It also doesn't cater the latest value and (a valid) query would result in 3 scans of the table; which seems a little over kill.

                              – Larnu
                              Nov 22 '18 at 12:44







                              That query won't run I'm afraid; for example a subquery in the SELECT needs to be wrapped in paranthesis(()). It also doesn't cater the latest value and (a valid) query would result in 3 scans of the table; which seems a little over kill.

                              – Larnu
                              Nov 22 '18 at 12:44















                              My mistake is that I give a solution hint for MySQL. And you can reduce the number of scans to 2, but then you are not sure about the correctness of the returned data

                              – bato3
                              Nov 22 '18 at 12:49





                              My mistake is that I give a solution hint for MySQL. And you can reduce the number of scans to 2, but then you are not sure about the correctness of the returned data

                              – bato3
                              Nov 22 '18 at 12:49













                              This is a SQL Server question, not MySQL.

                              – Larnu
                              Nov 22 '18 at 12:50





                              This is a SQL Server question, not MySQL.

                              – Larnu
                              Nov 22 '18 at 12:50


















                              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%2f53430982%2fset-column-value-based-on-another-columns-value%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

                              To store a contact into the json file from server.js file using a class in NodeJS

                              Redirect URL with Chrome Remote Debugging Android Devices

                              Dieringhausen