Need help creating a counter

  • Thread starter Thread starter Gary Shelton
  • Start date Start date
G

Gary Shelton

I am trying to complete the following in a query. It has two different
calculations.

Counter SKU Record_Counter
1 0783D 1
1 0783D 2
2 100 1
2 100 2
2 100 3
3 10110045 1
3 10110045 2
3 10110045 3
3 10110045 4
3 10110045 5
3 10110045 6
3 10110045 7
3 10110045 8
3 10110045 9
4 10110090 1
4 10110090 2
5 10110162 1
5 10110162 2
6 10110575 1
6 10110575 2
 
I assume you start with the second field and want to get the first and third
one, right?

I did tested the following (air code). May miss parenthesis or something
like that.


To get the third column, you can start with a driver table, a table, say
Iotas, with one field, iota, with values from 1 to, say, 99.

===============================
SELECT x.sku, Iotas.iota
FROM (SELECT sku, COUNT(*) As hm
FROM yourInitialTable
GROUP BY sku) AS x
INNER JOIN iotas
ON x.hm >= iotas.iota
===============================

should supply the second and third columns. It is a basic non-equi join. The
idea is to 'compress' the original data, to have no dup any more, here,
virtual table x has only one record per sku, then, to re-hydrate the thing
through the driver table supplying the 'counter'.


To get the first column, start with a query giving a list of distinct sku:

=====================
SELECT DISTINCT sku FROM yourInitialTable
=====================

Saved it under the name qud.

Then, to get the first column (together with the third one), try something
like:

========================
SELECT (SELECT COUNT(*)
FROM qud
WHERE sku <= x.sku) AS counter,

x.sku,

Iotas.iota AS record_counter

FROM (SELECT sku, COUNT(*) As hm
FROM yourInitialTable
GROUP BY sku) AS x

INNER JOIN iotas
ON x.hm >= iotas.iota
=============================


Note that it is a case where the sub-query cannot be immediately promoted
into a join.


Alternative.



It may be faster to do it with a join, but as pointed out, we need an extra
query before being able to do it.

The extra query:


-----------------------
SELECT a.sku, COUNT(*) AS rank
FROM qud AS a INNER JOIN qud AS b
ON a.sku >= b.sku
GROUP BY a.sku
-------------------------

saved as qrank and the top most query would be:


===============================
SELECT qrank.rank, x.sku, Iotas.iota
FROM
((SELECT sku, COUNT(*) As hm
FROM yourInitialTable
GROUP BY sku) AS x
INNER JOIN iotas ON x.hm>= iotas.iota)
INNER JOIN qrank ON x.sku=qrank.sku
===============================






Hoping it may help,
Vanderghast, Access MVP
 
Back
Top