问题
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