Sql Server: How to Group by Substring

Sql Server: How to Group by Substring

I have the following stored procedure to fetch data from a table. The table has a column "region" that contains value like "APAC: China" etc. for which I am using the substring function in order to remove the : and everything after it.

The below works except that it lists all records separately instead of grouping them by my substring. So I have e.g. several items with region "APAC" instead of just one with all of them appearing below.

My stored procedure:

CREATE PROCEDURE [dbo].[CountRegions]
AS
BEGIN
    SET NOCOUNT ON;
    SELECT      SUBSTRING(region, 1, CHARINDEX(':', region) - 1) AS region,
                COUNT(*) AS groupCount,
    FROM        SOPR_LogRequests
    WHERE       logStatus = 'active'
    GROUP BY    region
    ORDER BY    groupCount desc, region
    FOR XML PATH('regions'), ELEMENTS, TYPE, ROOT('ranks')
END

My result:

<ranks>
  <regions>
    <region>APAC</region>
    <groupCount>1</groupCount>
  </regions>
  <regions>
    <region>EMEA</region>
    <groupCount>1</groupCount>
  </regions>
  <regions>
    <region>APAC</region>
    <groupCount>1</groupCount>
  </regions>
  // ...
</ranks>

Expected result:

<ranks>
  <regions>
    <region>APAC</region>
    <groupCount>2</groupCount>
  </regions>
  <regions>
    <region>EMEA</region>
    <groupCount>1</groupCount>
  </regions>
  // ...
</ranks>

Can anyhone here help me with this ?

Thanks for any help, Tim.

1 Answer

Your group by would not know whether you are referring to the underlying column, or the output of your function code (it would assume the underlying column), so you need to repeat the code into the group by:-

CREATE PROCEDURE [dbo].[CountRegions]
AS
BEGIN
    SET NOCOUNT ON;
    SELECT      SUBSTRING(region, 1, CHARINDEX(':', region) - 1) AS region,
                COUNT(*) AS groupCount,
    FROM        SOPR_LogRequests
    WHERE       logStatus = 'active'
    GROUP BY    SUBSTRING(region, 1, CHARINDEX(':', region) - 1)
    ORDER BY    groupCount desc, region
    FOR XML PATH('regions'), ELEMENTS, TYPE, ROOT('ranks')
END
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.