Simple but complex SQL question, at least I couldn’t find a way out besides doing it externally (C #)

I have an SQL table that consists of only 1 column

Column Name
A 
A
A
B
B
B
B
C
D
D
E

I need SQL code that returns cut points. In the above table, it will return this:

Column Name
    3
    7
    8
    10
    11

3 - end A, and 7 - end B, and 8 - end C, etc.

See what you can come up with: =)

+3
source share
3 answers

Assuming that data can be sorted on yours Column, a plan should generate row numberfor each row and make group byto get your data points.

SQL Server 2000

DECLARE @YourTable TABLE (Col VARCHAR(1))
CREATE TABLE #TempTable (ID INTEGER IDENTITY(1, 1), Col VARCHAR(1))

SET IDENTITY_INSERT #TempTable OFF
INSERT INTO @YourTable (Col) VALUES ('A')
INSERT INTO @YourTable (Col) VALUES ('A')
INSERT INTO @YourTable (Col) VALUES ('A')
INSERT INTO @YourTable (Col) VALUES ('B')
INSERT INTO @YourTable (Col) VALUES ('B')
INSERT INTO @YourTable (Col) VALUES ('B')
INSERT INTO @YourTable (Col) VALUES ('B')
INSERT INTO @YourTable (Col) VALUES ('C')
INSERT INTO @YourTable (Col) VALUES ('D')
INSERT INTO @YourTable (Col) VALUES ('D')
INSERT INTO @YourTable (Col) VALUES ('E')

INSERT INTO #TempTable
SELECT      *
FROM        @YourTable
ORDER BY    Col

SELECT    MAX(ID)
FROM      #TempTable
GROUP BY  Col

DROP TABLE #TempTable

SQL Server 2005

DECLARE @Table TABLE (Col VARCHAR(1))

INSERT INTO @Table VALUES ('A')
INSERT INTO @Table VALUES ('A')
INSERT INTO @Table VALUES ('A')
INSERT INTO @Table VALUES ('B')
INSERT INTO @Table VALUES ('B')
INSERT INTO @Table VALUES ('B')
INSERT INTO @Table VALUES ('B')
INSERT INTO @Table VALUES ('C')
INSERT INTO @Table VALUES ('D')
INSERT INTO @Table VALUES ('D')
INSERT INTO @Table VALUES ('E')


SELECT  MAX(RowNumber)
FROM    (SELECT RowNumber = ROW_NUMBER() OVER (ORDER BY Col), Col
         FROM   @Table) t
GROUP BY Col
+16
source
with endings(columnname, ending) as
(
    select columnname, row_number() over (order by columnname) as 'ending'
    from theTable
)
select max(ending)
from endings
group by columnname
+3
source

Oracle:

, COL1,

SELECT COL1,MAX(ROWNUM)
  FROM TEST_CHARS
 GROUP BY COL1
 ORDER BY COL1;
+1

Source: https://habr.com/ru/post/1730403/


All Articles