referring to sum of elements in column with Microsoft Access 2010

Viewed 41

My employee's IT department refuses to install R for me (claiming the open source version is a security risk) and I tried to create reports with Microsoft Access 2010.

I got stuck trying to create a query on a simple table of hospital wards (for the purpose of keeping track of a data collection exercise):

example table

I did not manage to allocate each ward a sample size that would be proportional to its bed capacity (third column above) as I was not able to refer to the sum of the elements in the "bedCapacity" column. With Excel, I would try something like this:

Excel table

Cell D2 in Excel contains =INT(C2/SUM(C$2:C$6)*50)+1 and cells D3 to D6 according formulae.

Is there any way I can refer to the sum in the bedCapacity column in Access 2010? I tried creating a separate query that would sum up the the 'bedCapacity` column, however could not figure out how to refer to the value in that query.

I'm trying to use Access 2010 so I can create standardised reports for the data collectors on their progress (which is not easily possible with Excel 2010, as it requires too much manual manipulation - I tried pivot tables etc.).

Would be grateful for any insights.

2 Answers

Create and save this query to give you the total bed capacity from all wards.

SELECT Sum(bedCapacity) AS TotalBeds
FROM YourTable;

Replace YourTable with the name of your table, of course. For the rest of this answer, I will pretend you saved that query with the name qryGrandTotalBedCapacity.

Then you can use that query in another where you cross join it with your table. The cross join gives you a result set which pairs each row of one data source with every row of the other data source.

However, since qryGrandTotalBedCapacity returns only a single row, this amounts to just making the TotalBeds value available for every row of YourTable. And, from that starting point, it is easy to translate your Excel formula to the Access SQL equivalent.

SELECT
    y.ID,
    y.ward,
    y.bedCapacity,
    (INT((y.bedCapacity/q.TotalBeds) * 50) + 1) AS sampleSize
FROM YourTable AS y, qryGrandTotalBedCapacity AS q;

My RoundSum function will do that:

Public Sub ListSampleSizes(ByVal BedCapacity As Variant, ByVal SampleSum As Long)

    Dim SampleSizes As Variant
    Dim Item        As Long
    
    SampleSizes = RoundSum(BedCapacity, SampleSum)
    For Item = LBound(SampleSizes) To UBound(SampleSizes)
        Debug.Print Item + 1, BedCapacity(Item), SampleSizes(Item)
    Next
           
End Sub

Result:

 1             22            12 
 2             18            10 
 3             20            11 
 4             16            9 
 5             19            11 

Too much code to post here, but full code is for download at GitHub: VBA.Round

Related