Oracle FAQ Your Portal to the Oracle Knowledge Grid
HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US
 

Home -> Community -> Usenet -> c.d.o.server -> Re: SQL update question

Re: SQL update question

From: DA Morgan <damorgan_at_x.washington.edu>
Date: Mon, 22 Nov 2004 20:19:31 -0800
Message-ID: <1101183482.554638@yasure>


Kamal wrote:

> Hi everybody.
>
> If I have a table like this:
>
> col0(number) cnt (number)
>
> 0 (null)
> 0 (null)
> 0 (null)
> 1 (null)
> 1 (null)
> 2 (null)
>
> And I want:
>
> col0(number) cnt (number)
>
> 0 3
> 0 3
> 0 3
> 1 2
> 1 2
> 2 1
>
> where cnt is the count of the records with different values in col0:
> what would be the fastest single update to achieve this?
>
> I would do
>
> update t t1 set t1.cnt = (select count(*) from t t2
> where t1.col0 = t2.col0
> group by t2.col0);
>
> Is there a better way?
> I know there's a redundancy but I want it.
>
> Thank you.
>
> Kamal

One possible solution is:

UPDATE (
   SELECT col0, cnt
   FROM t) p
SET (p.col0, p.cnt) = (

    select col0, COUNT(*) CNT
    from t
    where p.col0 = col0
    group by col0);

Of course the plans as generated by DBMS_XPLAN are identical. At least on my machine. So not better ... just different.

-- 
Daniel A. Morgan
University of Washington
damorgan_at_x.washington.edu
(replace 'x' with 'u' to respond)
Received on Mon Nov 22 2004 - 22:19:31 CST

Original text of this message

HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US