Fill percentage of total field conditional on some other field with MS Access SQL
4
votes
1
answer
103
views
This question is an extension of [Fill percentage of total field with MS Access SQL](https://dba.stackexchange.com/questions/156749/fill-percentage-of-total-field-with-ms-access-sql) .
I have the following 2013 MS Access SQL query:
UPDATE MyTable
SET F = f / DSUM("f", "MyTable") ;
This query fills field
F
with the percentage over the total of some field f
, such that each one of the records F(i)
in field F
is given by:
F(i) = f(i)/SUM_i(f(i))
Both fields f
and F
belong to table MyTable
.
Now, I would like, instead of simply computing the percentage over the whole table, to do it by Date
, where Date
is a 3rd field also to be found in table MyTable
. I will make up an example for illustration purposes. Let's assume a simplified MyTable
with 2 records per date; then that's what I would like MyTable
to look like after executing my desired query... - see fields f
and F
:
| Date | Department | f | F |
|------------|------------|-----------|-----------|
| t1 | D1 | 2 | 40% |
| t1 | D2 | 3 | 60% |
| t2 | D1 | 1 | 20% |
| t2 | D2 | 4 | 80% |
... And this is how it is looking right now, after executing the query displayed above:
| Date | Department | f | F |
|------------|------------|-----------|-----------|
| t1 | D1 | 2 | 20% |
| t1 | D2 | 3 | 30% |
| t2 | D1 | 1 | 10% |
| t2 | D2 | 4 | 40% |
I have tried the following code, but none yielded what I wanted.
_Try #1_:
UPDATE MyTable
SET F = f / DSUM("f", "MyTable", "Date");
_Try #2_:
UPDATE MyTable
SET F = f / DSUM("f", "MyTable", "Date=Date");
Any ideas on how I could manage to do this?
**Note**: I have just called the two fields "f
" and "F
" here for illustration purposes, it is not how they are named in the actual DB.
----------
I will add here further tests that haven't worked out:
_Try #3_:
UPDATE MyTable
SET F = f / DSUM("f", "MyTable", "Date=" & Date);
_Try #4_: this has worked but only for a single Date
, the 1st one to be recorded - i.e. the one in the 1st row/record of the table MyTable
- for the rest of dates the value for F
is empty.
UPDATE MyTable
SET F = f / DSUM("f", "MyTable", "Date=#" & Date & "#");
Asked by Daneel Olivaw
(173 rep)
Nov 30, 2016, 04:30 PM
Last activity: Dec 1, 2016, 07:52 PM
Last activity: Dec 1, 2016, 07:52 PM