2012-05-24 55 views
0

我試圖用另一個表中的數據更新表列deletiondate但我得到「缺少表達式」的錯誤。有人可以幫我解決這個問題嗎?更新語句使用選擇和組丟失的表達式

基本上我想更新deletiondate列中的一個表,方法是將關鍵字段與另一個表連接起來並進行分組。如果日期爲01-JAN-0001且記錄數大於1,則需要更新01-JAN-0001否則我需要更新最大刪除日期值。

UPDATE語句我用:

update table1 db1 set deletiondate = 

SELECT 
CASE WHEN count(*)>1 and ( 
    (select 1 
    from table2 b 
    where b.loginid = a.loginid 
     and a.creationdate = b.creationdate 
     and b.deletiondate = '01-JAN-0001' 
    ) = 1) THEN '01-JAN-0001' ELSE to_char(MAX(deletiondate),'DD-MON-YYYY') END as deletiondate1 
FROM table2 a 
GROUP BY a.loginid, a.creationdate 
WHERE db1.userloginid = a.loginid and db1.usercreationdate = a.creationdate 
+0

在該SQL中沒有GROUP BY,是否如預期那樣? –

+0

@JirkaHanika - 由於格式不正確,「GROUP BY」被隱藏在代碼中。 – Tony

+2

'to_char'是什麼? –

回答

1

使用此格式:http://www.sqlfiddle.com/#!4/c46a6/2

update product set 
    (total_qty,max_qty) = 
(
    select sum(qty) as tot, max(qty) as maxq 
    from inv 
    where product_id = product.product_id 
    group by product_id 
) ; 

的樣本數據:

create table product(
    product_id int primary key, 
    product_name varchar(100), 
    total_qty int, 
    max_qty int 
); 

create table inv(
    inv_id int primary key, 
    product_id int references product(product_id), 
    qty int 
); 


insert into product(product_id,product_name) 
select 1,'KB' from dual 
union 
select 2, 'MSE' from dual 
union 
select 3, 'CPU' from dual; 

insert into inv(inv_id,product_id,qty) 
select 1,1,4 from dual 
union 
select 2,2,1 from dual 
union 
select 3,3, 3 from dual 
union 
select 4,1,1 from dual 
union 
select 5,2,2 from dual 
union 
select 6,1,5 from dual; 

查詢輸出:

| PRODUCT_ID | PRODUCT_NAME | TOTAL_QTY | MAX_QTY | 
|------------|--------------|-----------|---------| 
|   1 |   KB |  10 |  5 | 
|   2 |   MSE |   3 |  2 | 
|   3 |   CPU |   3 |  3 |