Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting rows in SQL Server by substrings

I am using SQL Server 2008 R2. Currently, I have a table that looks like the following:

   Text      DateLogged  SomeID  SomeOtherID
-----------------------------------------------
1234: Data   04/04/2014    1        190
3212: Text   04/04/2014    1        190
4332: Data   04/04/2014    1        190
1256: Data   04/04/2014    1        190

as well as the following SQL query:

SELECT RIGHT(Text, LEN(Text) - CHARINDEX(':', Text) - 1) AS Sub, DateLogged, SomeID, SomeOtherID
FROM   Example
WHERE  SomeOtherID = 190

I would like to get the counts of rows with the same substring (Sub) for a report that I am building with SSRS. However, I can't seem to find a way to group the query results by substring (FYI, the DateLogged and SomeID fields are used for grouping in the report). The report would look like the following:

Month    SomeID     Sub     Count
---------------------------------
April
            1
                    Data      3
                    Text      1

Any solution, whether it is on the query level or the report level, would be greatly appreciated!

like image 240
shawnsmlee Avatar asked Jul 11 '26 00:07

shawnsmlee


1 Answers

This counts the substrings:

SELECT RIGHT(Text, LEN(Text) - CHARINDEX(':', Text) - 1) AS Sub, count(*)
FROM   Example
WHERE  SomeOtherID = 190
GROUP BY RIGHT(Text, LEN(Text) - CHARINDEX(':', Text) - 1);

If you want the date and other id:

SELECT datepart(month, datelogged) as mon,
       RIGHT(Text, LEN(Text) - CHARINDEX(':', Text) - 1) AS Sub,
       someotherid, count(*)
FROM   Example
WHERE  SomeOtherID = 190
GROUP BY datepart(month, datelogged) as mon,
         RIGHT(Text, LEN(Text) - CHARINDEX(':', Text) - 1),
         SomeOtherId;
like image 68
Gordon Linoff Avatar answered Jul 13 '26 17:07

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!