简体   繁体   中英

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM