向 SQL 查询添加自定义列

发布于 2024-11-08 21:50:46 字数 359 浏览 0 评论 0原文

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

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

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

例如,

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

知道如何做到这一点吗? 谢谢!

Lets say I have a DB built like this:

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

what I need to do to add another column in which all the values having num "2" will be in.

e.g.

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

any idea how I can do this?
thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空城旧梦 2024-11-15 21:50:46

在此示例中,我使用 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"

In this example I am using SQLite, where the table Source already has a built-in rowid. Depending on the database you are using, you may need to add your own auto-incrementing integer column (i.e., integer primary key), but the idea is the same.

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"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文