Multiple Cases For Same Result ColumnSQL MAX of multiple columns?How to check if a column exists in a SQL Server table?Select columns from result set of stored procedureInserting multiple rows in a single SQL query?Insert results of a stored procedure into a temporary tableAltering a column: null to not nullSearch by nvarcharFind all tables containing column with specified name - MS SQL ServerOR is not supported with CASE Statement in SQL ServerGet the value of END AS column in case when in where clause

What is the lowest voltage that a microcontroller can successfully read on the analog pin?

Does wetting a beer glass change the foam characteristics?

Is it more effective to add yeast before or after kneading?

If the EU does not offer an extension to UK's Article 50 invocation, is the Benn Bill irrelevant?

How use custom order in folder on Windows 7 and 10

Is it really necessary to have a four hour meeting in Sprint planning?

Two trains move towards each other, a bird moves between them. How many trips can the bird make?

How do you use the interjection for snorting?

How to make interviewee comfortable interviewing in lounge chairs

A high quality contribution but an annoying error is present in my published article

Title Change now and Wage Increase Later

Is it right to extend flaps only in the white arc?

What is this utensil for?

Should the average user with no special access rights be worried about SMS-based 2FA being theoretically interceptable?

Is there any iPhone SE out there with 3D Touch?

What can a pilot do if an air traffic controller is incapacitated?

Why does NASA publish all the results/data it gets?

Why weren't the Death Star plans transmitted electronically?

Where are they calling from?

Guitar tuning (EADGBE), "perfect" fourths?

How to deal with my team leader who keeps calling me about project updates even though I am on leave for personal reasons?

The 100 soldier problem

2000s Animated TV show where teenagers could physically go into a virtual world

How to manage expenditure when billing cycles and paycheck cycles are not aligned?



Multiple Cases For Same Result Column


SQL MAX of multiple columns?How to check if a column exists in a SQL Server table?Select columns from result set of stored procedureInserting multiple rows in a single SQL query?Insert results of a stored procedure into a temporary tableAltering a column: null to not nullSearch by nvarcharFind all tables containing column with specified name - MS SQL ServerOR is not supported with CASE Statement in SQL ServerGet the value of END AS column in case when in where clause






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








1















Have a table where one of the columns has all of the info I need for a report.
I want to substring certain portions of this column as a column in this report, but the problem is that this column has results from 3 varying character lengths.



Example:



Row1: 20180101_ABC_12
Row2: 20180102_DEFG_23
Row3: 20180103_HIJKL_45


In this particular example I want the middle portion (eg. ABC) to be a column called 'Initials', problem is I am using CASE logic for each LEN. Not sure else how to achieve this.



My sample query below. It pulls all of the possible options, but as separate columns. What would I need to do to have these 3 options pull into one column, let's call it 'Initials'?



Thanks



SELECT
FileName
, CASE WHEN LEN(FileName) = 10 THEN SUBSTRING(FileName, 10, 3) ELSE NULL END
, CASE WHEN LEN(FileName) = 11 THEN SUBSTRING(FileName, 10, 4) ELSE NULL END
, CASE WHEN LEN(FileName) = 12 THEN SUBSTRING(FileName, 10, 5) ELSE NULL END
FROM File









share|improve this question
































    1















    Have a table where one of the columns has all of the info I need for a report.
    I want to substring certain portions of this column as a column in this report, but the problem is that this column has results from 3 varying character lengths.



    Example:



    Row1: 20180101_ABC_12
    Row2: 20180102_DEFG_23
    Row3: 20180103_HIJKL_45


    In this particular example I want the middle portion (eg. ABC) to be a column called 'Initials', problem is I am using CASE logic for each LEN. Not sure else how to achieve this.



    My sample query below. It pulls all of the possible options, but as separate columns. What would I need to do to have these 3 options pull into one column, let's call it 'Initials'?



    Thanks



    SELECT
    FileName
    , CASE WHEN LEN(FileName) = 10 THEN SUBSTRING(FileName, 10, 3) ELSE NULL END
    , CASE WHEN LEN(FileName) = 11 THEN SUBSTRING(FileName, 10, 4) ELSE NULL END
    , CASE WHEN LEN(FileName) = 12 THEN SUBSTRING(FileName, 10, 5) ELSE NULL END
    FROM File









    share|improve this question




























      1












      1








      1








      Have a table where one of the columns has all of the info I need for a report.
      I want to substring certain portions of this column as a column in this report, but the problem is that this column has results from 3 varying character lengths.



      Example:



      Row1: 20180101_ABC_12
      Row2: 20180102_DEFG_23
      Row3: 20180103_HIJKL_45


      In this particular example I want the middle portion (eg. ABC) to be a column called 'Initials', problem is I am using CASE logic for each LEN. Not sure else how to achieve this.



      My sample query below. It pulls all of the possible options, but as separate columns. What would I need to do to have these 3 options pull into one column, let's call it 'Initials'?



      Thanks



      SELECT
      FileName
      , CASE WHEN LEN(FileName) = 10 THEN SUBSTRING(FileName, 10, 3) ELSE NULL END
      , CASE WHEN LEN(FileName) = 11 THEN SUBSTRING(FileName, 10, 4) ELSE NULL END
      , CASE WHEN LEN(FileName) = 12 THEN SUBSTRING(FileName, 10, 5) ELSE NULL END
      FROM File









      share|improve this question
















      Have a table where one of the columns has all of the info I need for a report.
      I want to substring certain portions of this column as a column in this report, but the problem is that this column has results from 3 varying character lengths.



      Example:



      Row1: 20180101_ABC_12
      Row2: 20180102_DEFG_23
      Row3: 20180103_HIJKL_45


      In this particular example I want the middle portion (eg. ABC) to be a column called 'Initials', problem is I am using CASE logic for each LEN. Not sure else how to achieve this.



      My sample query below. It pulls all of the possible options, but as separate columns. What would I need to do to have these 3 options pull into one column, let's call it 'Initials'?



      Thanks



      SELECT
      FileName
      , CASE WHEN LEN(FileName) = 10 THEN SUBSTRING(FileName, 10, 3) ELSE NULL END
      , CASE WHEN LEN(FileName) = 11 THEN SUBSTRING(FileName, 10, 4) ELSE NULL END
      , CASE WHEN LEN(FileName) = 12 THEN SUBSTRING(FileName, 10, 5) ELSE NULL END
      FROM File






      tsql






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 28 at 17:02









      forpas

      44.9k6 gold badges13 silver badges34 bronze badges




      44.9k6 gold badges13 silver badges34 bronze badges










      asked Mar 28 at 16:42









      joru100joru100

      266 bronze badges




      266 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          2
















          In Tableau, you would accomplish this using a calculated field.



          Initials:



          CASE LEN(FileName)
          WHEN 10 THEN SUBSTRING(FileName, 10, 3)
          WHEN 11 THEN SUBSTRING(FileName, 10, 4)
          WHEN 12 THEN SUBSTRING(FileName, 10, 5)
          END


          Or maybe



          SUBSTRING(FileName
          ,10
          ,CASE LEN(FileName)
          WHEN 10 THEN 3
          WHEN 11 THEN 4
          WHEN 12 THEN 5
          END
          )


          But barring the more technical aspect, this can be solved with math (assuming your data is either limited to the 10, 11, and 12, or that the pattern holds):



          SUBSTRING(FileName
          ,10
          ,LEN(FileName)-7
          )





          share|improve this answer
































            1
















            You need 1 CASE statement covering every possible case and not 3 separate ones, because each one creates a new column:



            SELECT
            FileName
            , CASE LEN(FileName)
            WHEN 10 THEN SUBSTRING(FileName, 10, 3)
            WHEN 11 THEN SUBSTRING(FileName, 10, 4)
            WHEN 12 THEN SUBSTRING(FileName, 10, 5)
            ELSE NULL
            END AS Initials
            FROM File


            Another way to get everything between the 2 _:



            SELECT
            FileName
            , substring(
            left(FileName, len(FileName) - charindex('_', reverse(FileName) + '_')),
            charindex('_', FileName) + 1,
            len(FileName)
            ) AS Initials
            FROM File


            but from your logic I assume that the values in column FileName have the same patern:



            <9 digits>_<Initials>_<2 digits>


            If this is the case then you can get what you want like this:



            SELECT
            FileName
            , substring(FileName, 10, len(FileName) - 12) AS Initials
            FROM File





            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/4.0/"u003ecc by-sa 4.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%2f55402852%2fmultiple-cases-for-same-result-column%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              2
















              In Tableau, you would accomplish this using a calculated field.



              Initials:



              CASE LEN(FileName)
              WHEN 10 THEN SUBSTRING(FileName, 10, 3)
              WHEN 11 THEN SUBSTRING(FileName, 10, 4)
              WHEN 12 THEN SUBSTRING(FileName, 10, 5)
              END


              Or maybe



              SUBSTRING(FileName
              ,10
              ,CASE LEN(FileName)
              WHEN 10 THEN 3
              WHEN 11 THEN 4
              WHEN 12 THEN 5
              END
              )


              But barring the more technical aspect, this can be solved with math (assuming your data is either limited to the 10, 11, and 12, or that the pattern holds):



              SUBSTRING(FileName
              ,10
              ,LEN(FileName)-7
              )





              share|improve this answer





























                2
















                In Tableau, you would accomplish this using a calculated field.



                Initials:



                CASE LEN(FileName)
                WHEN 10 THEN SUBSTRING(FileName, 10, 3)
                WHEN 11 THEN SUBSTRING(FileName, 10, 4)
                WHEN 12 THEN SUBSTRING(FileName, 10, 5)
                END


                Or maybe



                SUBSTRING(FileName
                ,10
                ,CASE LEN(FileName)
                WHEN 10 THEN 3
                WHEN 11 THEN 4
                WHEN 12 THEN 5
                END
                )


                But barring the more technical aspect, this can be solved with math (assuming your data is either limited to the 10, 11, and 12, or that the pattern holds):



                SUBSTRING(FileName
                ,10
                ,LEN(FileName)-7
                )





                share|improve this answer



























                  2














                  2










                  2









                  In Tableau, you would accomplish this using a calculated field.



                  Initials:



                  CASE LEN(FileName)
                  WHEN 10 THEN SUBSTRING(FileName, 10, 3)
                  WHEN 11 THEN SUBSTRING(FileName, 10, 4)
                  WHEN 12 THEN SUBSTRING(FileName, 10, 5)
                  END


                  Or maybe



                  SUBSTRING(FileName
                  ,10
                  ,CASE LEN(FileName)
                  WHEN 10 THEN 3
                  WHEN 11 THEN 4
                  WHEN 12 THEN 5
                  END
                  )


                  But barring the more technical aspect, this can be solved with math (assuming your data is either limited to the 10, 11, and 12, or that the pattern holds):



                  SUBSTRING(FileName
                  ,10
                  ,LEN(FileName)-7
                  )





                  share|improve this answer













                  In Tableau, you would accomplish this using a calculated field.



                  Initials:



                  CASE LEN(FileName)
                  WHEN 10 THEN SUBSTRING(FileName, 10, 3)
                  WHEN 11 THEN SUBSTRING(FileName, 10, 4)
                  WHEN 12 THEN SUBSTRING(FileName, 10, 5)
                  END


                  Or maybe



                  SUBSTRING(FileName
                  ,10
                  ,CASE LEN(FileName)
                  WHEN 10 THEN 3
                  WHEN 11 THEN 4
                  WHEN 12 THEN 5
                  END
                  )


                  But barring the more technical aspect, this can be solved with math (assuming your data is either limited to the 10, 11, and 12, or that the pattern holds):



                  SUBSTRING(FileName
                  ,10
                  ,LEN(FileName)-7
                  )






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 28 at 17:06









                  AndyAndy

                  1,4482 gold badges24 silver badges58 bronze badges




                  1,4482 gold badges24 silver badges58 bronze badges


























                      1
















                      You need 1 CASE statement covering every possible case and not 3 separate ones, because each one creates a new column:



                      SELECT
                      FileName
                      , CASE LEN(FileName)
                      WHEN 10 THEN SUBSTRING(FileName, 10, 3)
                      WHEN 11 THEN SUBSTRING(FileName, 10, 4)
                      WHEN 12 THEN SUBSTRING(FileName, 10, 5)
                      ELSE NULL
                      END AS Initials
                      FROM File


                      Another way to get everything between the 2 _:



                      SELECT
                      FileName
                      , substring(
                      left(FileName, len(FileName) - charindex('_', reverse(FileName) + '_')),
                      charindex('_', FileName) + 1,
                      len(FileName)
                      ) AS Initials
                      FROM File


                      but from your logic I assume that the values in column FileName have the same patern:



                      <9 digits>_<Initials>_<2 digits>


                      If this is the case then you can get what you want like this:



                      SELECT
                      FileName
                      , substring(FileName, 10, len(FileName) - 12) AS Initials
                      FROM File





                      share|improve this answer































                        1
















                        You need 1 CASE statement covering every possible case and not 3 separate ones, because each one creates a new column:



                        SELECT
                        FileName
                        , CASE LEN(FileName)
                        WHEN 10 THEN SUBSTRING(FileName, 10, 3)
                        WHEN 11 THEN SUBSTRING(FileName, 10, 4)
                        WHEN 12 THEN SUBSTRING(FileName, 10, 5)
                        ELSE NULL
                        END AS Initials
                        FROM File


                        Another way to get everything between the 2 _:



                        SELECT
                        FileName
                        , substring(
                        left(FileName, len(FileName) - charindex('_', reverse(FileName) + '_')),
                        charindex('_', FileName) + 1,
                        len(FileName)
                        ) AS Initials
                        FROM File


                        but from your logic I assume that the values in column FileName have the same patern:



                        <9 digits>_<Initials>_<2 digits>


                        If this is the case then you can get what you want like this:



                        SELECT
                        FileName
                        , substring(FileName, 10, len(FileName) - 12) AS Initials
                        FROM File





                        share|improve this answer





























                          1














                          1










                          1









                          You need 1 CASE statement covering every possible case and not 3 separate ones, because each one creates a new column:



                          SELECT
                          FileName
                          , CASE LEN(FileName)
                          WHEN 10 THEN SUBSTRING(FileName, 10, 3)
                          WHEN 11 THEN SUBSTRING(FileName, 10, 4)
                          WHEN 12 THEN SUBSTRING(FileName, 10, 5)
                          ELSE NULL
                          END AS Initials
                          FROM File


                          Another way to get everything between the 2 _:



                          SELECT
                          FileName
                          , substring(
                          left(FileName, len(FileName) - charindex('_', reverse(FileName) + '_')),
                          charindex('_', FileName) + 1,
                          len(FileName)
                          ) AS Initials
                          FROM File


                          but from your logic I assume that the values in column FileName have the same patern:



                          <9 digits>_<Initials>_<2 digits>


                          If this is the case then you can get what you want like this:



                          SELECT
                          FileName
                          , substring(FileName, 10, len(FileName) - 12) AS Initials
                          FROM File





                          share|improve this answer















                          You need 1 CASE statement covering every possible case and not 3 separate ones, because each one creates a new column:



                          SELECT
                          FileName
                          , CASE LEN(FileName)
                          WHEN 10 THEN SUBSTRING(FileName, 10, 3)
                          WHEN 11 THEN SUBSTRING(FileName, 10, 4)
                          WHEN 12 THEN SUBSTRING(FileName, 10, 5)
                          ELSE NULL
                          END AS Initials
                          FROM File


                          Another way to get everything between the 2 _:



                          SELECT
                          FileName
                          , substring(
                          left(FileName, len(FileName) - charindex('_', reverse(FileName) + '_')),
                          charindex('_', FileName) + 1,
                          len(FileName)
                          ) AS Initials
                          FROM File


                          but from your logic I assume that the values in column FileName have the same patern:



                          <9 digits>_<Initials>_<2 digits>


                          If this is the case then you can get what you want like this:



                          SELECT
                          FileName
                          , substring(FileName, 10, len(FileName) - 12) AS Initials
                          FROM File






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 28 at 17:42

























                          answered Mar 28 at 17:04









                          forpasforpas

                          44.9k6 gold badges13 silver badges34 bronze badges




                          44.9k6 gold badges13 silver badges34 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%2f55402852%2fmultiple-cases-for-same-result-column%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

                              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

                              용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                              155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해