views:

98

answers:

3

I am trying to update records in an .mdb table with the number of records containing the same value

The sql below does not work but I think gives an indication of what I am trying to achieve.

UPDATE table1 AS A
INNER JOIN (SELECT PH_BSP , Count(PH_BSP) AS PHCOUNT  FROM table1 GROUP BY PH_BSP)  AS B
ON A.PH_BSP=B.PH_BSP
SET A.PH_SORT = B.PHCOUNT;

any ideas?

A: 

Have you tried something alike?

update table1 as a
    set a.ph_sort = (
        select COUNT(b.ph_bsp) as phcount
            from table1 b
            where b.ph_bsp = a.ph_bsp)

I'm assuming SQL Server here.

But this or something alike should do it, I guess.

Will Marcouiller
table is in an .mdb database, so access is the go here...I tried the above sql but get a message:"Operation must use an updateable query"
brett
This message says that there is no update possible to perform. This means that there was an error somehow, somewhere in the DML. In fact, I was trying to set a.ph_bsp = (select...) instead of a.ph_sort, in my sample code. Perhaps with this updated sample?
Will Marcouiller
@brett: try omitting `AS A`, maybe that's the reason why the table becomes not updateable
Michael Buen
still getting "Operation must use an updateable query" on both suggestions...
brett
+1  A: 

Untested, but setting out the statement thusly this should solve your issue

UPDATE A
SET A.PH_SORT = B.PHCOUNT
From table1 AS A
INNER JOIN (SELECT PH_BSP , Count(PH_BSP) AS PHCOUNT  FROM table1 GROUP BY PH_BSP)  AS B
ON A.PH_BSP=B.PH_BSP

Edit: Your problem might be from your sub query, I would try putting that part into a separate Access Query and see how it goes. From memory I used to have a lot of trouble with Access and subqueries, square brackets would also sometimes help, but unreliable from memory.

keith
+1 That is also a well known form which I didn't think of. =)
Will Marcouiller
in access this generates:Syntax error (missing operator) in query expression B.PHCOUNT From table1 AS A INNER JOIN (SELECT PH_BSP , Count(PH_BSP) AS PHCOUNT FROM table1 GROUP BY PH_BSP) AS B ON A.PH_BSP=B.PH_BSP
brett
A: 

If you are doing this in Access, you need to use a domain aggregate function:

UPDATE table1 
SET PH_SORT = DCount("PH_BSP","Table1","PH_BSP='" & PH_BSP & "'")

The above assumes that PH_BSP is a text field, drop the single quotes if it is numeric.

Remou
Thanks for the info. If the domain aggregate functions are the only way to do this for an access table then I think its back to 'group by' into a temp table and and joining to the original. I'm processing hunndreds of thousands of records per day (in many databses) and DCount is just too slow (like hours to slow) Thanks again for the help
brett