从查询多行插入VALUES

时间:2015-09-03 12:25:28

标签: sql postgresql

我在这个专栏中有一个表“RESULT”:

+--------+------+------------+--------+
| USERID | POIN |    DATE    |  DESC  |
+--------+------+------------+--------+
|      1 |   10 | 2015-08-03 | LOGIN  |
|      1 |   -1 | 2015-08-11 | LOGOUT |
|      3 |    5 | 2015-08-07 | INVITE |
|      2 |   30 | 2015-08-15 | LOGIN  |
|      2 |    5 | 2015-08-17 | INVITE |
|      2 |    3 | 2015-08-25 | LOGOUT |
+--------+------+------------+--------+

所以,我想在表“RESULT”中插入新值。所以这是新的价值观:

+--------+------+------------+--------+
| USERID | POIN |    DATE    |  DESC  |
+--------+------+------------+--------+
|      1 |    9 | 2015-09-01 | FREE   |
|      3 |    5 | 2015-09-01 | FREE   |
|      2 |   38 | 2015-09-01 | FREE   |
+--------+------+------------+--------+

DATE和DESC定义的值,但是poin是sum结果。如何在postgresql中执行此操作?

1 个答案:

答案 0 :(得分:1)

看起来你想要插入具有poin值和固定日期和desc值之和的新行。

你可以这样做:

INSERT INTO RESULT ("USERID", "POIN", "DATE", "DESC")
SELECT "USERID", SUM("POIN"), '2015-09-01', 'FREE'
FROM RESULT GROUP BY "USERID";

如果要查看要插入的行,可以运行不带第一行的语句。

Sample SQL Fiddle