向SQL查询添加自定义列

时间:2011-05-23 07:02:09

标签: sql

假设我有一个像这样构建的数据库:

NUM    VALUE    
 1      3.51
 2      hello
 1      3.487
 2      goodbye
 1      32.4
 2      foo

我需要做些什么来添加另一个列,其中所有值为“2”的值都将在其中。

e.g。

NUM     VALUE     value2
 1       3.51      hello      
 1       3.487     goodbye
 1      32.4       foo

任何想法我怎么能这样做? 谢谢!

1 个答案:

答案 0 :(得分:3)

在这个例子中,我使用的是SQLite,其中表Source已经有一个内置的rowid。根据您使用的数据库,您可能需要添加自己的自动递增整数列(即整数主键),但想法是相同的。

CREATE TABLE Source (num, value);
INSERT INTO Source (num, value) VALUES (1, 3.51);
INSERT INTO Source (num, value) VALUES (2, 'hello');
INSERT INTO Source (num, value) VALUES (1, 3.487);
INSERT INTO Source (num, value) VALUES (2, 'goodbye');
INSERT INTO Source (num, value) VALUES (1, 32.4);
INSERT INTO Source (num, value) VALUES (2, 'foo');

"1","3.51"
"2","hello"
"1","3.487"
"2","goodbye"
"1","32.4"
"2","foo"

SELECT a.num, a.value, b.value
FROM Source a
INNER JOIN Source b ON a.rowid = b.rowid - 1
WHERE a.num = 1 AND b.num = 2

"1","3.51","hello"
"1","3.487","goodbye"
"1","32.4","foo"