2

I need to represent the following records

DATA
000200AA
00000200AA
000020BCD
00000020BCD
000020ABC

AS

DATA    CNT
200AA   1
20BCD   2
20ABC   2

ANY IDEAS?

4

6 回答 6

8

USE patindex

select count(test) as cnt,
 substring(test, patindex('%[^0]%',test),len(test)) from (

  select ('000200AA') as test
  union
  select '00000200AA' as test
  union
  select ('000020BCD') as test
  union
  select ('00000020BCD') as test
  union
  select ('000020ABC') as test

  )ty
 group by substring(test, patindex('%[^0]%',test),len(test))
于 2012-05-18T15:51:40.320 回答
3

How about a nice recursive user-defined function?

CREATE FUNCTION dbo.StripLeadingZeros (
        @input varchar(MAX)
) RETURNS varchar(MAX)
BEGIN

    IF LEN(@input) = 0
        RETURN @input

    IF SUBSTRING(@input, 1, 1) = '0'
        RETURN dbo.StripLeadingZeros(SUBSTRING(@input, 2, LEN(@input) - 1))

    RETURN @input

END
GO

Then:

SELECT dbo.StripLeadingZeros(DATA) DATA, COUNT(DATA) CNT
FROM YourTable GROUP BY dbo.StripLeadingZeros(DATA)
于 2012-05-18T15:50:52.990 回答
1
DECLARE @String VARCHAR(32) = N'000200AA'

SELECT  SUBSTRING ( @String ,CHARINDEX(N'2', @String),LEN(@String))
于 2012-05-18T15:52:03.893 回答
1

Depending on the what you need to get the values this code may differ:

Assuming a simple right 5 chars as Barry suggested, you can use RIGHT(data, 5) and GROUP BY and COUNT to get your results

http://sqlfiddle.com/#!3/19ecd/2

于 2012-05-18T15:52:12.520 回答
0

take a look at the STUFF function

It inserts data into a string on a range

于 2012-05-18T15:53:55.093 回答
0

You can do this query:

SELECT RIGHT([DATA],LEN[DATA])-PATINDEX('%[1-9]%',[DATA])+1) [DATA], COUNT(*) CNT
FROM YourTable
GROUP BY RIGHT([DATA],LEN[DATA])-PATINDEX('%[1-9]%',[DATA])+1)
于 2012-05-18T15:55:06.837 回答