使用CASE和条件更新表(postgresql)

时间:2013-07-08 07:24:17

标签: sql postgresql postgresql-9.2

我有表格::

CREATE TABLE emp1
(
  eid integer NOT NULL,
  ename character varying(20),
  sid integer,
  ssid integer,
  CONSTRAINT pk_eid PRIMARY KEY (eid)
);

CREATE TABLE leave_type
(
  eid integer,
  lid integer,
  lnum integer,
  emp_bal integer,
  sno serial NOT NULL,
  CONSTRAINT pk_sno PRIMARY KEY (sno),
  CONSTRAINT fk_eid FOREIGN KEY (eid)
      REFERENCES emp1 (eid) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
);//emp_bal-->employee balance leaves which is considered as 8

CREATE TABLE result
(
  eid integer,
  lid integer,
  sd date,
  ed date,
  sida boolean,
  ssida boolean,
  rsno serial NOT NULL,
  CONSTRAINT pk_rsno PRIMARY KEY (rsno)
);

插入数据

emp1
-----
 eid | ename | sid | ssid
-----+-------+-----+------
   1 | a     |   2 |    8
   3 | c     |   4 |    9
   2 | b     |   3 |    8
   4 | d     |   2 |    8
   5 | e     |   2 |    8
   6 | f     |   4 |    9

(6行)

leave_type
----------
 eid | lid | lnum | emp_bal | sno
-----+-----+------+---------+-----
   1 |   0 |    1 |       8 |   1
   3 |   0 |    1 |       8 |   2
   5 |   0 |    1 |       8 |   3
   1 |   1 |    1 |       8 |   4
   1 |   2 |    2 |       8 |   5
(5 rows)

result
-------
 eid | lid |     sd     |     ed     | sida | ssida | rsno
-----+-----+------------+------------+------+-------+------
   1 |   0 | 2013-01-01 | 2013-01-01 | t    | f     |    1
   3 |   0 | 2013-01-09 | 2013-01-09 | t    | f     |    2
   5 |   0 | 2013-01-11 | 2013-01-11 | t    | f     |    3
   1 |   1 | 2013-02-14 | 2013-02-14 | t    | f     |    4
   1 |   2 | 2013-03-15 | 2013-03-16 | f    | t     |    5
(5 rows)

查询:

我想要更新批准表

CREATE TABLE approval
    (
      eid integer,
      lid integer,
      asid integer,
      bal integer
    );

作为输出

      eid | lid | sid |bal
     -----+-----+---+--
       1 |   0 | 2 | 7
       3 |   0 | 4 | 7
       5 |   0 | 2 | 7
       1 |   1 | 2 | 6
       1 |   2 | 8 | 4
    (5 rows)

条件:: 我尝试了这个查询,以获取sid进入批准表,如下所述::

CASE WHEN r.sida='t' 
  THEN (update approval set a.asid=e.sid where a.eid=e.eid from emp1 e,approval a)
WHEN r.ssida='t'
  THEN (update approval set a.asid=e.ssid where a.eid=e.eid from emp1 e,approval a) 
ELSE 0
END

我希望甚至可以根据sid验证来更新平衡列,即..,

  

CASE如果r.sida ='t'则emp1中的bal = emp1.emp_bal-1和emp_bal应该   如果r.ssida ='t',则从批准其他更新为bal的最新值   那么bal = emp_bal-2和emp1中的emp_bal应该更新到最新版本   来自批准的bal值

有没有办法解决这个问题?

最后,我希望看到所有获得批准并获得批准的员工离职,并留下余额留下!!

完整的详细信息在[SQL FIDDLE](http://sqlfiddle.com/#!12/3e6a7/18

1 个答案:

答案 0 :(得分:5)

你做错了。

在Update语句中使用Case语句,而不是在Case Case中使用Update Statement。

喜欢

Update **Table**
Set **Col1**= 

Case when **Col10=1** then 5

else case when **Col10=2** THEN 6

**ELSE 10** END  
**ELSE 15** END