SQL Create Unique Value Flag












1














There are lots of questions/answers about selecting unique values in a MySQL query but I haven't seen any on creating a unique value flag.



I'm have a customer_ID that can appear more than once in a query output. I want to create new column that flags whether the customer_ID is unique or not (0 or 1).



The output should look something like this:



ID     | Customer ID      | Unique_Flag
1 | 1234 | 1
2 | 2345 | 1
3 | 2345 | 0
4 | 5678 | 1


Please let me know if anybody needs clarifications.










share|improve this question





























    1














    There are lots of questions/answers about selecting unique values in a MySQL query but I haven't seen any on creating a unique value flag.



    I'm have a customer_ID that can appear more than once in a query output. I want to create new column that flags whether the customer_ID is unique or not (0 or 1).



    The output should look something like this:



    ID     | Customer ID      | Unique_Flag
    1 | 1234 | 1
    2 | 2345 | 1
    3 | 2345 | 0
    4 | 5678 | 1


    Please let me know if anybody needs clarifications.










    share|improve this question



























      1












      1








      1







      There are lots of questions/answers about selecting unique values in a MySQL query but I haven't seen any on creating a unique value flag.



      I'm have a customer_ID that can appear more than once in a query output. I want to create new column that flags whether the customer_ID is unique or not (0 or 1).



      The output should look something like this:



      ID     | Customer ID      | Unique_Flag
      1 | 1234 | 1
      2 | 2345 | 1
      3 | 2345 | 0
      4 | 5678 | 1


      Please let me know if anybody needs clarifications.










      share|improve this question















      There are lots of questions/answers about selecting unique values in a MySQL query but I haven't seen any on creating a unique value flag.



      I'm have a customer_ID that can appear more than once in a query output. I want to create new column that flags whether the customer_ID is unique or not (0 or 1).



      The output should look something like this:



      ID     | Customer ID      | Unique_Flag
      1 | 1234 | 1
      2 | 2345 | 1
      3 | 2345 | 0
      4 | 5678 | 1


      Please let me know if anybody needs clarifications.







      mysql sql unique






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 23 at 7:20









      jarlh

      28.4k52138




      28.4k52138










      asked Nov 23 at 4:45









      Daniel Galletta

      1591114




      1591114
























          3 Answers
          3






          active

          oldest

          votes


















          1














          You seem to want to mark the first occurrence as unique, but not others. So, let's join in the comparison value:



          select t.*,
          (id = min_id) as is_first_occurrence
          from t join
          (select customer_id, min(id) as min_id
          from t
          group by customer_id
          ) tt
          on t.customer_id = tt.customer_id;


          For most people, a "unique" flag would mean that the overall count is "1", not that this is merely the first appearance. If that is what you want, then you can use similar logic:



          select t.*,
          (id = min_id) as is_first_occurrence,
          (cnt = 1) as is_unique
          from t join
          (select customer_id, min(id) as min_id, count(*) as cnt
          from t
          group by customer_id
          ) tt
          on t.customer_id = tt.customer_id;


          And, in MySQL 8+, you would use window functions:



          select t.*,
          (row_number() over (partition by customer_id order by id) = 1) as is_first_occurrence,
          (count(*) over (partition by customer_id) = 1) as is_unique
          from t;





          share|improve this answer





























            0














            You can try below



            select id,a.customerid, case when cnt=1 then 1 else 0 end as Unique_Flag
            from tablename a
            left join
            (select customerid, count(*) as cnt from tablename
            group by customerid
            )b on a.customerid=b.customerid





            share|improve this answer





























              0














              Sample table exampleYou can use lead function as given below to get the required output.



              SELECT ID, CUSTOMER_ID,
              CASE
              WHEN CUSTOMER_ID != CUSTOMER_ID_NEXT THEN 1
              ELSE 0
              END AS UNIQUE_FLAG FROM
              (SELECT ID, CUSTOMER_ID,LEAD(CUSTOMER_ID, 1, 0) OVER (ORDER BY CUSTOMER_ID) AS CUSTOMER_ID_NEXT FROM TABLE)T






              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%2f53440767%2fsql-create-unique-value-flag%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                1














                You seem to want to mark the first occurrence as unique, but not others. So, let's join in the comparison value:



                select t.*,
                (id = min_id) as is_first_occurrence
                from t join
                (select customer_id, min(id) as min_id
                from t
                group by customer_id
                ) tt
                on t.customer_id = tt.customer_id;


                For most people, a "unique" flag would mean that the overall count is "1", not that this is merely the first appearance. If that is what you want, then you can use similar logic:



                select t.*,
                (id = min_id) as is_first_occurrence,
                (cnt = 1) as is_unique
                from t join
                (select customer_id, min(id) as min_id, count(*) as cnt
                from t
                group by customer_id
                ) tt
                on t.customer_id = tt.customer_id;


                And, in MySQL 8+, you would use window functions:



                select t.*,
                (row_number() over (partition by customer_id order by id) = 1) as is_first_occurrence,
                (count(*) over (partition by customer_id) = 1) as is_unique
                from t;





                share|improve this answer


























                  1














                  You seem to want to mark the first occurrence as unique, but not others. So, let's join in the comparison value:



                  select t.*,
                  (id = min_id) as is_first_occurrence
                  from t join
                  (select customer_id, min(id) as min_id
                  from t
                  group by customer_id
                  ) tt
                  on t.customer_id = tt.customer_id;


                  For most people, a "unique" flag would mean that the overall count is "1", not that this is merely the first appearance. If that is what you want, then you can use similar logic:



                  select t.*,
                  (id = min_id) as is_first_occurrence,
                  (cnt = 1) as is_unique
                  from t join
                  (select customer_id, min(id) as min_id, count(*) as cnt
                  from t
                  group by customer_id
                  ) tt
                  on t.customer_id = tt.customer_id;


                  And, in MySQL 8+, you would use window functions:



                  select t.*,
                  (row_number() over (partition by customer_id order by id) = 1) as is_first_occurrence,
                  (count(*) over (partition by customer_id) = 1) as is_unique
                  from t;





                  share|improve this answer
























                    1












                    1








                    1






                    You seem to want to mark the first occurrence as unique, but not others. So, let's join in the comparison value:



                    select t.*,
                    (id = min_id) as is_first_occurrence
                    from t join
                    (select customer_id, min(id) as min_id
                    from t
                    group by customer_id
                    ) tt
                    on t.customer_id = tt.customer_id;


                    For most people, a "unique" flag would mean that the overall count is "1", not that this is merely the first appearance. If that is what you want, then you can use similar logic:



                    select t.*,
                    (id = min_id) as is_first_occurrence,
                    (cnt = 1) as is_unique
                    from t join
                    (select customer_id, min(id) as min_id, count(*) as cnt
                    from t
                    group by customer_id
                    ) tt
                    on t.customer_id = tt.customer_id;


                    And, in MySQL 8+, you would use window functions:



                    select t.*,
                    (row_number() over (partition by customer_id order by id) = 1) as is_first_occurrence,
                    (count(*) over (partition by customer_id) = 1) as is_unique
                    from t;





                    share|improve this answer












                    You seem to want to mark the first occurrence as unique, but not others. So, let's join in the comparison value:



                    select t.*,
                    (id = min_id) as is_first_occurrence
                    from t join
                    (select customer_id, min(id) as min_id
                    from t
                    group by customer_id
                    ) tt
                    on t.customer_id = tt.customer_id;


                    For most people, a "unique" flag would mean that the overall count is "1", not that this is merely the first appearance. If that is what you want, then you can use similar logic:



                    select t.*,
                    (id = min_id) as is_first_occurrence,
                    (cnt = 1) as is_unique
                    from t join
                    (select customer_id, min(id) as min_id, count(*) as cnt
                    from t
                    group by customer_id
                    ) tt
                    on t.customer_id = tt.customer_id;


                    And, in MySQL 8+, you would use window functions:



                    select t.*,
                    (row_number() over (partition by customer_id order by id) = 1) as is_first_occurrence,
                    (count(*) over (partition by customer_id) = 1) as is_unique
                    from t;






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 23 at 12:39









                    Gordon Linoff

                    756k35291399




                    756k35291399

























                        0














                        You can try below



                        select id,a.customerid, case when cnt=1 then 1 else 0 end as Unique_Flag
                        from tablename a
                        left join
                        (select customerid, count(*) as cnt from tablename
                        group by customerid
                        )b on a.customerid=b.customerid





                        share|improve this answer


























                          0














                          You can try below



                          select id,a.customerid, case when cnt=1 then 1 else 0 end as Unique_Flag
                          from tablename a
                          left join
                          (select customerid, count(*) as cnt from tablename
                          group by customerid
                          )b on a.customerid=b.customerid





                          share|improve this answer
























                            0












                            0








                            0






                            You can try below



                            select id,a.customerid, case when cnt=1 then 1 else 0 end as Unique_Flag
                            from tablename a
                            left join
                            (select customerid, count(*) as cnt from tablename
                            group by customerid
                            )b on a.customerid=b.customerid





                            share|improve this answer












                            You can try below



                            select id,a.customerid, case when cnt=1 then 1 else 0 end as Unique_Flag
                            from tablename a
                            left join
                            (select customerid, count(*) as cnt from tablename
                            group by customerid
                            )b on a.customerid=b.customerid






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 23 at 4:48









                            fa06

                            10.8k2917




                            10.8k2917























                                0














                                Sample table exampleYou can use lead function as given below to get the required output.



                                SELECT ID, CUSTOMER_ID,
                                CASE
                                WHEN CUSTOMER_ID != CUSTOMER_ID_NEXT THEN 1
                                ELSE 0
                                END AS UNIQUE_FLAG FROM
                                (SELECT ID, CUSTOMER_ID,LEAD(CUSTOMER_ID, 1, 0) OVER (ORDER BY CUSTOMER_ID) AS CUSTOMER_ID_NEXT FROM TABLE)T






                                share|improve this answer




























                                  0














                                  Sample table exampleYou can use lead function as given below to get the required output.



                                  SELECT ID, CUSTOMER_ID,
                                  CASE
                                  WHEN CUSTOMER_ID != CUSTOMER_ID_NEXT THEN 1
                                  ELSE 0
                                  END AS UNIQUE_FLAG FROM
                                  (SELECT ID, CUSTOMER_ID,LEAD(CUSTOMER_ID, 1, 0) OVER (ORDER BY CUSTOMER_ID) AS CUSTOMER_ID_NEXT FROM TABLE)T






                                  share|improve this answer


























                                    0












                                    0








                                    0






                                    Sample table exampleYou can use lead function as given below to get the required output.



                                    SELECT ID, CUSTOMER_ID,
                                    CASE
                                    WHEN CUSTOMER_ID != CUSTOMER_ID_NEXT THEN 1
                                    ELSE 0
                                    END AS UNIQUE_FLAG FROM
                                    (SELECT ID, CUSTOMER_ID,LEAD(CUSTOMER_ID, 1, 0) OVER (ORDER BY CUSTOMER_ID) AS CUSTOMER_ID_NEXT FROM TABLE)T






                                    share|improve this answer














                                    Sample table exampleYou can use lead function as given below to get the required output.



                                    SELECT ID, CUSTOMER_ID,
                                    CASE
                                    WHEN CUSTOMER_ID != CUSTOMER_ID_NEXT THEN 1
                                    ELSE 0
                                    END AS UNIQUE_FLAG FROM
                                    (SELECT ID, CUSTOMER_ID,LEAD(CUSTOMER_ID, 1, 0) OVER (ORDER BY CUSTOMER_ID) AS CUSTOMER_ID_NEXT FROM TABLE)T







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Nov 23 at 13:46

























                                    answered Nov 23 at 9:36









                                    Vivek Khandelwal

                                    1246




                                    1246






























                                        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.





                                        Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                        Please pay close attention to the following guidance:


                                        • 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%2f53440767%2fsql-create-unique-value-flag%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

                                        Contact image not getting when fetch all contact list from iPhone by CNContact

                                        count number of partitions of a set with n elements into k subsets

                                        A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks