开发者

A simple but challenging SQL Question, at least I couldn't find a way out except doing it externally (c#)

I have an SQL Table which consists of 1 column only

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

I need an SQL Code that returns the cut points. For the table above, it will return this:

Column Name
    3
    7
    8
    10
    11

3 is the end of A's and 7 is the end of B's and 8 is the end of C's and so on...

Let's see what开发者_StackOverflow社区 can you come up with :=)


Assuming the data can be sorted on your Column, the plan is to generate a row number for each row and do a group by to retrieve 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


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


Solution for Oracle:

Assuming the name of the column is COL1,

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜