Access SQL - Create Row For Every 10 Rows And Remainder Found In Group

人走茶凉 提交于 2019-12-24 11:34:53

问题


I can't conceptualize how to do this exclusively with SQL.

Say I have a query that would probably be the subquery in the solution to this problem that produced:

Color     |  Count
Brown     |  25
Yellow    |  5
Blue      |  35

Using the above result set, I would like a query with the following:

Color
Brown
Brown
Brown
Yellow
Blue
Blue
Blue
Blue

An alternative solution would be to take the count and do something like:

SELECT -Int((-Count(*)/10)) AS Expr1, Color
FROM ColorTable
group by test.Source_City

Which, using the above data would produce:

Color     |  Count
Brown     |  3
Yellow    |  1
Blue      |  4

A solution for this would be to take the Count and write a row for each 1.


回答1:


So we have our test data in a table named [InitialCounts]

Color   Count
------  -----
Blue       35
Brown      25
Yellow      5

and a "numbers table" named [Numbers] containing

   n
----
   1
   2
   3
...
9999

(or as high as it needs to go, based on the largest number of rows we expect to derive for each color, below).

The query

SELECT 
    Color, 
    Int(CDbl(Count)/10 + 0.5) AS NewCount
FROM InitialCounts

returns

Color   NewCount
------  --------
Blue           4
Brown          3
Yellow         1

and if we want to produce the repeating rows for each color we can just do

SELECT NewCounts.Color
FROM
    Numbers,
    (
        SELECT 
            Color, 
            Int(CDbl(Count)/10 + 0.5) AS NewCount
        FROM InitialCounts
    ) AS NewCounts
WHERE Numbers.n <= NewCounts.NewCount
ORDER BY NewCounts.Color

returning

Color 
------
Blue  
Blue  
Blue  
Blue  
Brown 
Brown 
Brown 
Yellow


来源:https://stackoverflow.com/questions/21787559/access-sql-create-row-for-every-10-rows-and-remainder-found-in-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!