Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

tsql - Is there a way of getting a proportional section of an SQL table?

I'm trying to split a single query into 4 parts, for readability purposes.

Having it as a single query, while adequate, isn't "pretty" for display purposes.

An example would be a query that brings in something akin to the below.

SELECT Column1Number
      ,Column2Text
FROM TableExample
WHERE Column1Number BETWEEN 1 AND 100

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For this you could use NTILE. NTILE is T-SQL's way of dividing rows as evenly as possible.

--==== 1. Sample Data
DECLARE @table TABLE (SomeNbr INT IDENTITY, SomeValue VARCHAR(50));
INSERT @table(SomeValue) SELECT TOP (11) NEWID() FROM sys.all_columns;

--==== Solution
SELECT 
  TileGroup = NTILE(4) OVER (ORDER BY t.SomeNbr), t.SomeNbr, t.SomeValue 
FROM   @table AS t;

Returns:

TileGroup   SomeNbr  SomeValue
----------- -------- ---------------
1           1        C3DB121B-C353-4...
1           2        A6C40211-D53B-4...
1           3        A2089286-1106-4...
2           4        3392E634-1D5E-4...
2           5        9006F0EB-1FDB-4...
2           6        831175BF-2783-4...
3           7        339216A6-AB6C-4...
3           8        29EAEECA-27E9-4...
3           9        CA302532-40F1-4...
4           10       29A41096-A786-4...
4           11       E0CA6CD4-FCB4-4...

Note that the performance of NTILE is not spectacular. For better performance you can use an NTally Table as this is the fastest method for evenly dividing rows; far more performance than NTILE. There's a little more work required though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...