単一の選択でそれを行うことができるとは思わない。AdventureWorks カーソルを使用できます。
create table my_Strings
(
my_string varchar(50)
)
insert into my_strings values('A'),('A'),('B'),('C'),('A'),('B'),('B') -- this method will only work on SQL Server 2008
--select my_String from my_strings
declare @temp_result table(
string varchar(50),
nr int)
declare @myString varchar(50)
declare @myLastString varchar(50)
declare @nr int
set @myLastString='A' --set this with the value of your FIRST string on the table
set @nr=0
DECLARE string_cursor CURSOR
FOR
SELECT my_string as aux_column FROM my_strings
OPEN string_cursor
FETCH NEXT FROM string_cursor into @myString
WHILE @@FETCH_STATUS = 0 BEGIN
if (@myString = @myLastString) begin
set @nr=@nr+1
set @myLastString=@myString
end else begin
insert into @temp_result values (@myLastString, @nr)
set @myLastString=@myString
set @nr=1
end
FETCH NEXT FROM string_cursor into @myString
END
insert into @temp_result values (@myLastString, @nr)
CLOSE string_cursor;
DEALLOCATE string_cursor;
select * from @temp_result
結果:
A 2
B 1
C 1
A 1
B 2